Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This looks like a homework problem, so I will try to give you some good advice.</p> <p>First, read the description of the fscanf function and the description of the "%s" conversion.</p> <p>Here is a snip from the description I have for "%s":</p> <blockquote> <p>Matches a sequence of non-white-space characters; the next pointer must be a pointer to a character array that is long enough to hold the input sequence and the terminating null character (’\0’), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first.</p> </blockquote> <p>Here are the two important points:</p> <ul> <li>Each of your input lines contains numbers and whitespace characters. So the function will read a number, reach whitespace, and stop. It will not read 9 characters.</li> <li>If it did read 9 characters, you do not have enough room in your array to store the <strong>10 bytes</strong> required. Note that a "terminating null character" will be added. 9 characters read, plus 1 null, equals 10. This is a common mistake in C programming and it is best to learn now to always account for the terminating null in any C string.</li> </ul> <p>Now, to fix this to read characters into a two dimensional array: You need to use a different function. Look through your list of C stdio functions.</p> <p>See anything useful sounding?</p> <p>If you haven't, I will give you a hint: fread. It will read a fixed number of bytes from the input stream. In your case you could tell it to always read 9 bytes.</p> <p>That would only work if each line is <strong>guaranteed</strong> to be padded out to 9 characters.</p> <p>Another function is fgets. Again, carefully read the function documentation. fgets is another function that appends a terminating null. However! In this case, if you tell fgets a size of 9, fgets will only read 8 characters and it will write the terminating null as the 9th character.</p> <p>But there is even another way! Back to fscanf! </p> <p>If you look at the other conversion specifiers, you could use "%9c" to read 9 characters. If you use <em>this</em> operation, it <strong>will not</strong> add a terminating null to the string. </p> <p>With both fread and fscanf "%9c" if you wanted to use those 9 bytes as a string in other functions such as printf, you would need to make your buffers 10 bytes and after every fread or fscanf function you would need to write <code>save[9] = '\0'</code>.</p> <p>Always read the documentation carefully. C string functions <em>sometimes</em> do it one way. <em>But not always.</em></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload