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';