[英]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.