Reputation: 385
I'm trying to read in a file that has different types to read in (integers, chars). This is relatively simple, yet I'm confused on which method to use to read in these different values.
I'm using fgets
to make sure the file isn't at the end, i.e;
char line[MAX_CHARS];
char ch;
FILE *infile = fopen("file.txt", "r");
const int MAX_CHARS = 50;
while(fgets(line, MAX_CHARS, infile) != NULL)
Given the input;
-Flight one
83, 34
X XX X
X X
-Flight two
....
I want to print the line that starts with a dash, send the integers to a method, and then print the X's and spaces. So, my code for this would be:
if(line[0] == '-')
{
printf("%s\n", line);
}
else if(2==sscanf(line, "%d%d", &long, &lat))
{
coordinates(long, lat);
}
I used scanf
to try to read the X's and spaces, but it doesn't work at all. getchar()
doesn't seem to work either, so should I start over and instead read each char
individually instead of a char
array?
EDIT: So I did as someone suggested, this is my updated code to read in spaces and X's, but it is clearly not reading right, as it's not going to the next line of X's.
else
{
while(line[++index] != '\0')
{
if(line[index] == ' ')
{
printf("%c", '.');
}
else if(line[index] == 'X')
{
printf("%c", '*');
}
}
}
For output;
*Flight one
.......*Flight two
Upvotes: 4
Views: 606
Reputation: 30489
scanf(line, " %c", &ch)
/* ^ */
The space before percent will cause scanf
to ignore all whitespace characters (space, tab, newline) if present.
i.e. condition if(ch == ' ')
will be always false
.
In your question, this is not something that you like, so remove this whitespace.
EDIT Also as suggested by Barak Manos
I think that for the second line you need to scan
"%d, %d"
instead of"%d%d"
.
Upvotes: 3