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

C++中cout写在gets()前却在其执行后才输出的问题求助

C++统计元音程序的问题:输出滞后与未定义行为

你的代码与运行现象

代码:

#include <iostream>
#include <cstdio>
using namespace std;

int main() {
    char str[50];
    int vow;
    cout<<"Type a sentence";
    gets(str);
    for(int i=0; str[i]!='\0';i++){
        switch(str[i]){
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u': vow++;
        }
    }
    cout<<"There are "<<vow<<" vowels in the string "<<str;
    return 0;
}

运行输出:

hello world
Type a sentenceThere are 3 vowels in the string hello world

1. 输出滞后的原因与解决

cout默认是行缓冲模式,当输出内容不带换行符\n且未手动刷新缓冲区时,内容会暂存到内存缓冲区,不会立刻显示在控制台。你写的cout<<"Type a sentence";没有换行,导致提示语被暂时缓存,直到后续输出操作才被一起打印。

解决方式二选一:

  • 在提示语末尾加换行:cout<<"Type a sentence\n";
  • 手动强制刷新缓冲区:cout<<"Type a sentence"<<flush;

2. 未初始化变量的严重问题

你定义的int vow;没有初始值,直接执行vow++会读取内存中随机的垃圾值,导致统计结果完全不可靠。必须初始化变量:int vow = 0;

3. 废弃函数的替换

gets()函数因存在缓冲区溢出风险,已在C++11标准中被废弃,推荐使用更安全的替代方案:

  • 使用cin.getline()读取字符串:cin.getline(str, sizeof(str));
  • 使用fgets():fgets(str, sizeof(str), stdin);(注意该函数会读取输入的换行符,需额外处理)

修复后的完整代码

#include <iostream>
#include <cstdio>
using namespace std;

int main() {
    char str[50];
    int vow = 0; // 初始化统计变量
    cout << "Type a sentence: " << flush; // 强制刷新缓冲区,确保提示语及时显示
    cin.getline(str, sizeof(str)); // 替换不安全的gets()
    
    for(int i=0; str[i]!='\0';i++){
        switch(str[i]){
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
        case 'A': // 新增大写元音的判断
        case 'E':
        case 'I':
        case 'O':
        case 'U':
            vow++;
            break; // 添加break,避免后续case被意外触发
        }
    }
    cout << "There are " << vow << " vowels in the string " << str << endl;
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 14:24:16