简体   繁体   中英

Ignoring whitepace with fscanf or fgets?

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM