[英]Ignoring whitepace with fscanf or 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.