c - 从键盘读取字符串时出现意外输出
问题描述
这个程序正在返回一些我无法理解的东西。附件是O/P简单程序的截图,用于查找空格数、制表符等。
我错过了什么?
#include <stdio.h>
#include <string.h>
int main() {
int count[] = { 0, 0, 0 }; /* 0 is spaces, 1 is tabs and 2 for newline. */
int string;
printf("Enter the paragraph: \n");
while ((string = getchar()) != EOF) {
if (string == ' ')
count[0]++;
else if (string == '\t')
count[1]++;
else if (string == '\n')
count[2]++;
}
printf("There are %d Spaces.\n", count[0]);
printf("There are %d Tabs.\n", count[1]);
printf("There are %d Newlines.\n", count[2]);
return 0;
}
解决方案
从屏幕截图中可以看出,您输入的内容Ctrl-Z是向程序发出文件结束信号。虽然这适用于 MS/DOS 和 Windows 终端等遗留系统,但此组合键在 linux 等 unix 系统上具有不同的含义:它会导致当前进程被其正在运行的 shell 父进程挂起。稍后可以使用该fg
命令恢复该过程。
要在此系统上发出文件结束信号,您应该键入Ctrl-D。
你的程序应该会产生预期的结果。代码看起来不错,尽管命名string
一个int
从getchar()
. 这样的变量通常被命名为c
.
推荐阅读
- reactjs - React-bootstrap 和深色 UI
- javascript - 下拉菜单在移动视图中未按预期工作
- apache-spark - Spark-HBase - GCP 模板 (2/3) - json4s 的版本问题?
- sql - 确定值的语言:阿拉伯语英语 SQL netezza
- memory-leaks - JVM内存泄漏诊断(jemalloc)
- node.js - Cookie 未在本地开发 Express REST API + react SPA 中设置
- html - 为什么宽度为百分比的浮点数在具有兄弟姐妹的容器中的行为与宽度为像素的容器内的行为不同?
- linux - 有没有办法更新从 arch wiki 安装的 visual-studio-code-bin
- python - 如何通过 Django 上的请求字段过滤 ListView
- android - 是否必须为所有视图(例如 ConstraintLayout)设置视图 ID?