2013-06-25 25 views
-1

假设我有一个文件的读取:阅读使用C中的fscanf另一个新线

//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

+0

'fscanf(fpin,“%[^ \ n]”,input)'相同,但是有空格 – chux

+0

什么是“输入”? – 0decimal0

+0

@PHIfounder它的字符串 –

回答

0

而不是使用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 
+0

好的......但实际上,该文件超过2行,我不应该知道它包含多少行。我只知道第一行是2个数字,第二行是一个字符串,第三行2个数字等,我需要使用这两个数字来做一些事情,然后使用这个字符串,所以..... btw,老师推荐我们使用fscanf ... –

+0

将2次读取放入一个循环中以处理N对线,注意结果== EOF(-1)以指示完成读取文件。如果你想使用'fscanf()',试试'result = fscanf(fpin,“%d%d”,&i [0],&i[1]);''和result = fscanf(fpin,“%[^ \ n]” ,input);'。注意前导空格消耗空白,包括之前未读的'\ n'。 – chux

0

您提供的代码将读取程序中的所有行(while循环的每次迭代一行),而不仅仅是第一行。 [我刚刚测试过]