假设我有一个文件要读取:
//it may contain more than 2 lines
12 6
abadafwg
假设现在我已经阅读了这样的第一行:
char input[999];
while(!feof(fpin))
{
fscanf(fpin, " %[^\n]", input);
//do something here with these numbers
//should do something here to read 2nd line
}
这是我的问题,如何读取该文件的第二行? 请帮忙QAQ
最佳答案
建议不要使用 fscanf(fpin, "%[^\n]", input)
,而是使用 fgets()
,因为这样可以防止缓冲区溢出。您可以将其用于这两行,然后根据需要进行解析。
if (fgets(input, sizeof(input), fpin) == 0) {
// handle error, EOF
}
int i[2];
int result = sscanf(input,"%d %d", &i[0], &i[1]);
switch (result) {
case -1: // eof
case 0: // missing data
case 1: // missing data
case 2: // expected
}
if (fgets(input, sizeof(input), fpin) == 0) {
// handle error, EOF
}
// use the 'abadfwg just read
关于c - 在 C 中使用 fscanf 读取另一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17287916/