【发布时间】:2017-01-22 16:00:36
【问题描述】:
我有一个从标准输入读取字符串的函数,它基于answer from here,
char* ReadString (FILE* f) {
int chr;
int n=0;
size_t size=4;
char *st=(char*)malloc(size*sizeof(char));
while (((chr=fgetc(f))!='\n') && (chr != EOF) ) {
st[n]=chr;
if (n+1==size)
st=(char*)realloc(st,(size+=8)*sizeof(char));
n++;
}
st[n]='\0';
return (char*)realloc(st,sizeof(char)*n);
}
功能正常,但我发现了一个问题。
int k;
printf("number\n");
scanf("%d",&k);
while (!loop) { //infinite loof for tests
printf("Name of the file and distination\n");
fname= ReadString(stdin);
printf("\"%s\"\n",fname);
}
现在我会遇到分段错误。好吧,据我了解,问题是在scanf之后,在stdin中留下了“\ n”。如果我把
while ( getchar() != '\n' ); // clean stdin
fname= ReadString(stdin);
我不会得到分段错误,第一个字符串会完美读取,但下一个字符串将无法正确读取,我需要输入两次。 为什么 (((chr=fgetc(f))!='\n') && (chr != EOF) ) 不起作用? -------------答案--------------
根据下面的答案,这里是未来的代码。
char* ReadString (FILE* f) {
int chr;
int n=0;
size_t size=4;
char *st=(char*)malloc(size);
bool loop=false;
while (!loop) {
while (((chr=fgetc(f))!='\n') && (chr != EOF) ) {
st[n]=chr;
if (n+1==size)
st=(char*)realloc(st,(size+=8)*sizeof(char));
n++;
}
loop=true;
if (n==0)
loop=false;
}
if (n!=0 )
st = (char*)realloc(st,sizeof(char)*n);
st[n]='\0';
return st;
}
【问题讨论】:
-
不要投
malloc()。 -
乘以
sizeof (char)是多余的:sizeof (char)定义为 1。