首页 > 解决方案 > 用 scanf 只读第一个字符

问题描述

我正在尝试使用 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

标签: c

解决方案


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

使用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);
}

推荐阅读