Monday, May 24, 2010

How do I input a word from a file using fscanf in the C language? Do I declare an array and use %s?

If you can just give me an example using fscanf to read from a file, one word at a time. I guess we will read til end of file. I want to read 3 words in. Does fscanf ignore whitespace? Will I have to type the 3 words with a hard return in my file?

How do I input a word from a file using fscanf in the C language? Do I declare an array and use %s?
Try the following:


char str [255];


char s_wrd1[80];


char s_wrd2[80];


char s_wrd3[80];





fscanf(tFile, "%s", str);


sscanf(str, "%s %s %s", s_wrd1, s_wrd2, s_wrd3);





The first 3 words will be stored in s_wrd1, s_wrd2 and s_wrd3 variables.





About the hard return, it doesn't matter whether you have it or not.
Reply:Check out this page:


http://www.cse.ucsc.edu/classes/cmps101/...





It gives and example program using the fscanf function.





And yes, I it ignores whitespace. Hard returns will not matter, because it will reach the EOF (End Of File) and return EOF.





FILE in_file;


in_file = fopen(filename, "r");


fscanf(in_file, "%s", %26amp;variable)





Good luck!


No comments:

Post a Comment