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

C++股东验证程序无法暂停接收输入及无限循环问题咨询

程序无限循环与无法接收输入的原因分析及修复

你的程序出现无限循环、无法正常接收输入的问题,核心原因有三个:

1. 输入缓冲区的换行残留导致无限循环

用cin.get(input, 32)读取输入时,它会在遇到换行符\n时停止读取,但不会把这个换行符从输入缓冲区中移除。下一次调用cin.get()时,会直接读取这个残留的换行符,导致input变成空字符串。程序会不断跳过用户输入,陷入无限循环,看起来就像“无法暂停接收输入”。

2. 字符串比较逻辑错误,永远匹配不上股东名单

你用input == keep_sh[i]比较输入的char数组和string类型的股东姓名,这完全错了:

  • input是char数组名,本质是指向数组首元素的指针;keep_sh[i]是string对象。
  • 这个比较其实是在比指针地址,永远不可能相等,所以所有输入都会被判定为未授权,内层循环会执行两次,然后进入外层循环的下一轮。

3. 末尾break的作用误解

  • 取消注释break时,外层while(true)循环只会跑一次就终止,所以验证环节提前结束。
  • 保留注释时,因为前面输入缓冲区和比较逻辑的问题,程序直接陷入无限循环。

修复方案

以下是调整后的完整代码,解决了所有问题:

#include <iostream>
#include <fstream>
#include <string>
#include <limits>
using namespace std;

int main(){
    ifstream name_sh("shareholders.dat");
    if (!name_sh.is_open()) {
        cout << "Failed to open shareholders.dat" << endl;
        return 1;
    }
    string keep_sh[1000];
    string line;
    int counter = 0;
    // 改用getline逐行读取,确保所有股东名单都被正确加载
    while (getline(name_sh, line)) {
        keep_sh[counter] = line;
        counter++;
    }
    name_sh.close();

    while(true){
        cout << "Please tell your name or press Q to exit ";
        string input;
        // 用getline读取整行输入,避免换行符残留
        getline(cin, input);
        if(input == "Q") break;

        bool authorized = false;
        for(int i=0; i < counter; i++){
            if(input == keep_sh[i]){
                cout << "You are welcome." << endl;
                authorized = true;
                break;
            }
        }
        if(authorized){
            cout << "Next." << endl;
            continue;
        }
        // 第一次输入错误,提示重新输入
        cout << "Write the official name in the formal way ";
        getline(cin, input);
        authorized = false;
        for(int i=0; i < counter; i++){
            if(input == keep_sh[i]){
                cout << "You are welcome." << endl;
                authorized = true;
                break;
            }
        }
        if(!authorized){
            cout << "Sorry, but you are not allowed." << endl;
        }
        cout << "Next." << endl;
    }
    return 0;
}

关键修复点

  • 改用getline(cin, input)读取整行输入,彻底解决换行符残留问题。
  • 全程用string类型存储和比较姓名,避免指针比较的错误,逻辑更直观。
  • 优化文件读取逻辑,用getline逐行读取,确保所有股东名单都被正确加载。
  • 增加文件打开失败的判断,提升程序健壮性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 09:59:50