Ignoring white with fscanf or fgets?

I was wondering if there is a way to ignore spaces using the fscanf or fgets function. My text file has two lines in each line, which may or may not be separated by a space. I need to read two characters and put them in another 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;
}
+3
source share
1 answer

Using a space ( " ") in fscanf format forces it to read and discard spaces in the input until it finds a character without spaces, leaving that character without spaces in the input as the next character to be read, So you can do such things , as:

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
+5
source

All Articles