1. AAAA needs 5 characters of storage, not 4
2. Unlike fgets, the count you supply to scanf does not take into account the need for a \0.
3. Trying to use sizeof() with scanf is horrible. There is no easy way to automatically tell scanf what the size of the array is.
4. while(feof(input)== 0) using feof() to control a loop is bad. http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1046476070&id=1043284351
Salem, thank you!!! All I've done is change the size of
and it seems to be working nicely. Could you please tell me why four characters (like, AAAA or BBBB) require an array of size 5? Thank you!
P.S. Also, I noticed your status, maybe you can tell me what's wrong with void main()? I know that it has something to do with the way compiler interpretes it, but I don't know what exactly the problem is.
Because when you are reading data from the file, it is read in the form of string and in your case, its C string.
The thing about C strings is that other than the characters it holds, it reserves a extra space at the end of the character array for the null character ('\0') which signifies the end of the C style or character array style string.
So when you are reading "AAAA" in your case, its actually is :
As you can see the last character is the null character which is automatically appended at the end of character arrays so that they can be treated as strings. This null character even doesn't show up when you query the length of the string using strlen( ) and hence is a common mistake made by beginners to assume that C strings only require the size equivalent to the number of characters they contain.
So in your previous code, you were using an array of size 4 which caused the null character to be copied to a location which doesn't belong to you and it overwrote the memory which you don't own. This normally leads to what is known as "Segmentation Error" i.e. modifying or touching memory which doesn't belong to you.
Hence changing the size from 4 to 5 caused your code to function correctly. Also consider changing from three sscanf( ) statements to a single fgets( ) and sscanf( ) which leads to a more robust and elegeant solution.
You basically have two choices
- learn dialect C, which is specific to your current compiler, and which has to be re-learnt for every new compiler you come across. And also endure the constant nagging of many people to do the "right thing".
- learn ANSI C, which will work exactly the same on any ANSI-C compiler you will come across.
You've already seen that compilers do not trap every possible problem, so you should never regard the absense of warnings as the absense of bugs (or poor portability, style or what have you).