簡體   English   中英

如何在while循環中使用cin?

[英]How do I use cin in a while loop?

我試圖讓用戶使用帶有數組和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設置a=0從第0個索引開始填充。

while(a < numberofplayers){

}

您的最后一次迭代超出了數組的大小。 您需要將其更改為

while(a < numberofplayers)

另外,請注意,不再使用關鍵字goto。 我建議在這里使用一段時間

while(true){
    cout<<"number of players";
    cin>>numberofplayers
    if(numberofplayers is valid input){
        break;
    }
    cout<<"bad input";
}

這里有一個關於stackoverflow的問題,廣泛討論了goto的使用: GOTO仍然被認為有害嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM