Ignoring whitepace with fscanf or fgets?
Asked Answered
H

1

3

I was wondering if there is any way to ignore whitespace with either the fscanf or fgets function. My text file has two chars on each line that may or may not be separated by a space. I need to read the two chars and place each one in a different array.

file = fopen(argv[1], "r");
if ((file = fopen(argv[1], "r")) == NULL) {
    printf("\nError opening file");
}
while (fscanf(file, "%s", str) != EOF) {
    printf("\n%s", str);
    vertexArray[i].label = str[0];
    dirc[i] = str[1];
    i += 1;
}
Harar answered 9/11, 2012 at 21:29 Comment(5)
fscanf(file, " %c %c", &str[0], &str[1])?Imeldaimelida
Why are you opening the file twice?Cascade
I just accidentally left the extra fopen in there, no reason. Thank you Daniel! :)Harar
I don't understand if you want to ignore just the first space, or also the others.Tyrontyrone
I wanted to ignore all white-space. So it will just read one char and skip any amount of white space there maybe to get the next char. =DHarar
S
6

Using a space (" ") in the fscanf format causes it to read and discard whitespace on the input until it finds a non-whitespace character, leaving that non-whitespace character on the input as the next character to be read. So you can do things like:

fscanf(file, " "); // skip whitespace
getc(file);        // get the non-whitespace character
fscanf(file, " "); // skip whitespace
getc(file);        // get the non-whitespace character

or

fscanf(file, " %c %c", &char1, &char2); // read 2 non-whitespace characters, skipping any whitespace before each
Substructure answered 9/11, 2012 at 22:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.