c - 用 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
解决方案
您的代码读取输入中的每个字符,而不是每行的第一个字符。
使用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);
}
推荐阅读
- python - 为什么keyword.kwlist不包含'async'和'await'?
- laravel - 试图获取非对象的属性“post_title”
- php - apache log_level 不会改变
- java - Java AES解密十六进制
- javascript - 删除两个数组javascript之间的不常见项目
- eclipse - 使用 XULRunner 时如何在 SWT 浏览器窗口中打开 pdf 文件?
- node.js - 使用和不使用托管服务部署 NodeJs 应用程序
- excel - VBA 代码:从 HTTP 响应收到的表中获取元素值
- c++ - 带有 swig 的模块名称
- asp.net - 获取正在浏览网站的用户详细信息