【问题标题】:Ignoring whitepace with fscanf or fgets?忽略 fscanf 或 fgets 的空白?
【发布时间】:2012-11-09 21:29:50
【问题描述】:

我想知道是否有任何方法可以使用 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])?
  • 为什么要打开文件两次?
  • 我只是不小心把多余的 fopen 放在那里,没有理由。谢谢丹尼尔! :)
  • 我不明白你是想忽略第一个空格,还是忽略其他空格。
  • 我想忽略所有的空白。所以它只会读取一个字符并跳过任何数量的空白,可能会得到下一个字符。 =D

标签: c fgets scanf


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多