2015-10-19 4 views
1

Я использую функцию fscanf в коде ac для чтения файла, содержащего 1 строку слов, разделенных пробелами, но, например, если первое слово 1234 , тогда, когда я печатаю его, вывод 234, однако другие слова в файле читаются правильно, любые идеи?fscanf не читает первый символ первого слова (в)

FILE* file = fopen(path, "r"); 

char arr = getc(file); 

char temp[20]; 

while(fscanf(file,"%s",temp)!= EOF && i<= column) 
{ 
printf("word %d: %s\n",i, temp); 
} 
+0

Хорошо, я сдаюсь, что вызов getc для, если не читать символ? –

+0

@MartinJames Я думал, что он прочитает весь файл и поместит его в массив символов. – AMH9

ответ

1

Вот посланной код, с моими комментариями

When asking a question about a run time problem, 
post code that cleanly compiles, and demonstrates the problem 

FILE* file = fopen(path, "r"); 
// missing check of `file` to assure the fopen() was successful 

char arr = getc(file); 
// this consumed the first byte of the file, (answers your question) 

char temp[20]; 

while(fscanf(file,"%s",temp)!= EOF && i<= column) 
// missing length modifier. format should be: "%19s" 
// 19 because fscanf() automatically appends a NUL byte to the input 
// 19 because otherwise the input buffer could be overrun, 
// resulting in undefined behaviour and possible seg fault event 
// should be checking (also) for returned value == 1 
// this will fail as soon as an `white space` is encountered 
// as the following call to fscanf() will not read/consume the white space 
// suggest a leading space in the format string to consume white space 
{ 
    printf("word %d: %s\n",i, temp); 
    // the variable 'i' is neither declared nor modified 
    // within the scope of the posted code 
} 
3

char arr = getc (file);

Возможно, над строкой вызывается первый символ.

+0

Я удалил этот код, потому что понял, что на самом деле мне это не нужно. – AMH9

+0

если он решает вашу проблему, пожалуйста, примите ответ. – Kamal

+0

Я не могу принять ответ в течение первых 10 минут после публикации вопроса. – AMH9

1
char arr = getc(file); 

читает первый символ из потока файлов и перебирает файл поток файла

+0

Как один вызов getc() перебирает итерацию файла? – user3629249

+0

@ user3629249 http://www.cplusplus.com/reference/cstdio/getc/: внутренний указатель положения файла затем переходит к следующему символу. –

+0

Вопрос о 'c' not 'C++' – user3629249

Смежные вопросы