gpt4 book ai didi

c++ - 如何在 while 循环中使用 cin?

转载 作者:太空宇宙 更新时间:2023-11-04 16:21:35 25 4
gpt4 key购买 nike

我试图让用户使用带有数组和 cin 的 while 循环来输入他们的名字,但是在输入最后一个人的名字之后,程序崩溃了而不是继续前进。有没有办法解决这个问题,还是我需要完全更改代码?我也是 c++ 的新手,所以可以尽可能简单地给出任何答案吗?

#include <iostream>
#include <string>

using namespace std;

int main()
{
unsigned int numberofplayers;
number://loop back here if more than 4 players
cout << "Number of players: ";
cin >> numberofplayers;
if(numberofplayers > 4 || numberofplayers < 1){
cout << "Invalid number, please enter a number from 1 to 4." << endl;
goto number;
}
string name[numberofplayers];
cout << "Enter your name" << endl;
int a = 1;
while(a < numberofplayers + 1){
cout << "Player " << a << ": ";
cin >> name[a];
cout << "Hello, " << name[a] << "." << endl;
a++;
}

}

最佳答案

您可能会遇到数组索引越界,因此请将您的 while 循环更改为此并设置 a=0 从第 0 个索引开始填充。

while(a < numberofplayers){

}

关于c++ - 如何在 while 循环中使用 cin?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16114826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com