I am trying to read a text file. There are three sections in the file. The first line always initialises the size of a piece of land, the following lines up to the '&' apply characteristics of the land, then the last few lines describe movement through the land.
Example input:
4x4
(0,0)
(3,3)
&
(0,0)>(0,1)>
(0,2)>(0,3)
So far, I have got the 4x4 to be stored as needed but, after this, how do I:
My code that does not work:
/* process first line */
while (c != "\n") {
scanf("%dx%d%c", &row, &col, &c);
printf("The land is %d high and %d wide.%c", row, col, c);
}
/* process until '&' is found */
while (c = getchar() != '&') {
printf("c=%c\n", c);
}
/* process rest of file */
while (c = getchar() != EOF) {
/* do something else */
}
There are several issues that you have.
First of all, a character constant is denoted by single quotes, like so:
while (c != '\n')
Second of all, instead of using x
in the format string, you can use %*c
to eat all the characters, like this:
scanf("%d%*c%d%c", &row, &col, &c);
You should also add extra parentheses here to properly check inequality, like this:
while ((c = getchar()) != '&')
Same here:
while ((c = getchar()) != EOF)