用fscanf或fgets忽略空格?

我想知道是否有任何方法可以忽略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格式的空格( " " )会使其读取并丢弃输入上的空格,直到找到非空白字符,并将输入上的非空白字符作为要读取的下一个字符。 所以你可以这样做:

 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