You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++中读取回车作为程序执行的标志?

问题描述

我的程序可正常检测存储在字符变量中的空格并输出zero,但之前无法检测回车键输出one(已将错误转义序列'/n'改为'\n')。我仅尝试将回车键存入字符变量并通过if语句检测作为标志但失败,目前使用cin.get(a)的方式已能正常输出one,想了解更多将回车键存入变量以实现检测的方法。

原代码如下:

#include <iostream>
using namespace std;
int main()
{
char a;
cin.get(a);
if(a=='\n')
cout<<"one";
if(a==' ')
cout<<"zero";
return 0;
}
可捕获回车键的其他方法
  • 使用getchar()函数
    getchar()会从标准输入读取单个字符,包括空白字符(换行、空格等),无需额外设置,直接赋值给字符变量即可检测回车:
#include <iostream>
using namespace std;
int main()
{
    char a = getchar();
    if(a == '\n')
        cout << "one";
    if(a == ' ')
        cout << "zero";
    return 0;
}
  • 关闭cin的空白符跳过功能
    默认情况下cin >>会自动跳过空白字符(空格、换行、制表符),通过noskipws操纵符关闭这个特性,就能直接读取回车:
#include <iostream>
using namespace std;
int main()
{
    char a;
    cin >> noskipws >> a;
    if(a == '\n')
        cout << "one";
    if(a == ' ')
        cout << "zero";
    return 0;
}
  • 使用scanf()函数
    scanf("%c", &a)不会自动跳过空白字符,输入回车时会将'\n'存入变量a,实现检测:
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
    char a;
    scanf("%c", &a);
    if(a == '\n')
        cout << "one";
    if(a == ' ')
        cout << "zero";
    return 0;
}

内容的提问来源于stack exchange,提问作者Ahmed Abdullah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 09:51:30