【问题标题】:Read only first character with scanf用 scanf 只读第一个字符
【发布时间】:2019-03-24 03:23:59
【问题描述】:

我正在尝试使用 scanf 仅读取每行的第一个字符。

有了这个输入:

c 文件:myciel3.col

c 来源:Michael Trick (trick@cmu.edu)

c 描述:基于 Mycielski 变换的图形。

c 无三角形(团号 2)但增加

c 着色数

p 边缘 11 20

对不起,我的英语不好。

int main(int argc, char *argv[]) {
    char option;
    int countC = 0;
    int countP = 0;
    while(scanf("%c",&option) != EOF) {
        if(option == 'c') countC++;
        else if (option == 'p') countP++;
    }
    printf("c: %d\tp: %d\n",countC, countP);
    return (0);
}

我希望输出 C:5 和 P:1,但实际输出是 c:15 p:2

【问题讨论】:

  • 是真实姓名和邮箱吗?如果是这样,将它们匿名化可能是明智之举。
  • @Broman scanf() 可以返回 EOF。
  • 为什么不直接使用getchar()scanf() 一次读取一个字符是多余的。
  • @Shawn 我的立场是正确的。非常确定它始终是一个非负值,表示成功分配的数量,但我错了。

标签: c


【解决方案1】:

您的代码会读取输入中的每个字符,而不是每行的第一个字符。

使用fgets 或任何其他获得一行的函数。

#include <stdio.h>

int main(int argc, char *argv[]) {
    char option[255];
    int countC = 0;
    int countP = 0;
    while(fgets(option, 255, stdin) != NULL) {
        if(option[0] == 'c') countC++;
        else if (option[0] == 'p') countP++;
    }
    printf("c: %d\tp: %d\n",countC, countP);
    return (0);
}

【讨论】:

  • 一个查询。如果现在我想得到“p edge 11 20”的两个数字。 else if (option[0] == 'p') { sscanf(option, "%d", &v); }
  • 说有n1, n2整数变量:sscanf(option, "p edge %d %d", &amp;n1, &amp;n2);
猜你喜欢
  • 2016-08-16
  • 2022-11-24
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
  • 2013-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多