使用fscanf或fgets时如何忽略空格?

3

我想知道是否有办法在fscanf或fgets函数中忽略空格。我的文本文件每行有两个字符,可能用空格分隔,也可能不用。我需要读取这两个字符,并将它们分别放入不同的数组中。

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

fscanf(file, " %c %c", &str[0], &str[1]) - Daniel Fischer
你为什么要打开文件两次? - user529758
我只是不小心多写了一个fopen,没有任何原因。谢谢你,Daniel! :) - Will Lewis
我不明白你是想忽略第一个空格还是所有的空格。 - Ramy Al Zuhouri
我想忽略所有的空格。因此,它将只读取一个字符并跳过可能存在的任何数量的空格以获取下一个字符。=D - Will Lewis
1个回答

6

在fscanf格式中使用空格(" ")会导致它在输入中读取并丢弃空格,直到找到一个非空格字符,将该非空格字符留在输入中作为下一个要读取的字符。因此,您可以执行以下操作:

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

或者

fscanf(file, " %c %c", &char1, &char2); // read 2 non-whitespace characters, skipping any whitespace before each

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接