简体   繁体   English

用fscanf或fgets忽略空格?

[英]Ignoring whitepace with fscanf or fgets?

I was wondering if there is any way to ignore whitespace with either the fscanf or fgets function. 我想知道是否有任何方法可以忽略fscanf或fgets函数的空格。 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. 使用fscanf格式的空格( " " )会使其读取并丢弃输入上的空白,直到找到非空白字符,并将输入上的非空白字符留作要读取的下一个字符。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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