int read_line(char str[], int n)
{
int ch,i=0;
while((ch=getchar()) != '\n')
if(i<n)
str[i++]=ch;
str[i]='\0'; /*terminates string*/
return i; /*number of characters stored*/
}
這個函數中當需要讀入的字符比較多時(超過n),結束時的str[i]='\0'不合理的話,這條語句該怎麼修改啊?
沒有什麼好辦法,你可以動態分配:
int n = 100;
char *str = new char[100];
while((ch=getchar()) != '\n')
{
if(i>n)
{
n *= 2;
char * str2 = new char[n * 2];
memcpy(str2, str, 0, n / 2);
delete str[];
str=str2;
}
str[i++]=ch;
}
str[i]='\0';