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

C++中for循环无输出且无限运行问题排查

代码问题排查与修复

1. 导致程序无响应的核心原因:错误的for循环结构

你在while循环内部写的for (i=0;i++;)是完全错误的for循环语法:

  • 标准for循环的结构是for(初始化; 循环条件; 递增操作),而你的写法中循环条件是i++,初始i=0时,i++会先返回0(布尔值为false),循环体直接跳过不执行。
  • 外层的while (cont == "yes")因为初始cont是"yes",会无限循环执行空的for循环,导致程序一直运行但没有任何输入输出提示。

解决方法:直接删除这个多余的for循环,你的逻辑是每次while循环添加一个饮品,不需要嵌套for循环。

2. 其他需要修复的问题

  • vector初始化错误:vector<string> beverages(0,0);第二个参数是int类型,但vector<string>的元素是string,会导致编译错误,应该改为vector<string> beverages;(空vector);更合理的是直接用vector<beverage> beverages;存储整个饮品对象,而非拆分属性存到string数组里。
  • 输入读取局限性:cin >> name这类写法只能读取不含空格的字符串,若饮品名称或描述有空格(比如"Orange Juice")会读取不完整,建议改用getline(cin, name),同时要处理前一次输入留下的换行符。
  • 类成员函数命名优化:getName()这类函数更适合改为返回值类型(比如string getName()),toString()可改为printInfo()更符合语义。

修复后的完整代码

#include <iostream>
#include <vector>
#include <string>
#include <limits>

using namespace std;

class beverage{
public:
    string name;
    string description;
    float serveSize;
    int calories;
    float price;

    void setName(){
        cout << "请输入饮品名称: " << endl;
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        getline(cin, name);
    }
    void setDescription(){
        cout << "请输入饮品描述: " << endl;
        getline(cin, description);
    }
    void setServeSize(){
        cout << "请输入饮品容量: " << endl;
        cin >> serveSize;
    }
    void setCalories(){
        cout << "请输入饮品热量: " << endl;
        cin >> calories;
    }
    void setPrice(){
        cout << "请输入饮品价格: " << endl;
        cin >> price;
    }
    void printInfo(){
        cout << "饮品名称: " << name << endl;
        cout << "饮品描述: " << description << endl;
        cout << "容量: " << serveSize << endl;
        cout << "热量: " << calories << endl;
        cout << "价格: " << price << endl;
    }
};

int main(){
    vector<beverage> beverages;
    string cont = "yes";
    beverage obj;

    while (cont == "yes"){
        obj.setName();
        obj.setDescription();
        obj.setServeSize();
        obj.setCalories();
        obj.setPrice();
        
        beverages.push_back(obj);
        cout << "是否继续添加饮品? (yes/no): " << endl;
        cin >> cont;
    }

    cout << "\n所有饮品信息如下:" << endl;
    for (auto &bev : beverages){
        bev.printInfo();
        cout << "------------------------" << endl;
    }

    return 0;
}

修复说明

  • 移除了多余且错误的for循环,让程序能正常执行输入逻辑。
  • 改用vector<beverage>存储完整的饮品对象,数据结构更合理,便于后续操作。
  • 优化了输入方式,支持带空格的名称和描述,同时处理了输入缓冲区的换行符问题。
  • 调整了类内函数的命名,使其更符合语义。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 19:16:24