簡體   English   中英

C ++ GetLine()問題,命令行程序

[英]C++ GetLine() Problem, Command Line Program

我正在為我的編程類編寫該程序,它有很多愚蠢的約束,例如我必須使用嵌套的if語句,並且必須使用cin.getLine()來獲得玩家的名字。 應該抓住每個球員的名字並計算他們的擊球平均值。

這不是整個程序,而是直到出現錯誤的部分為止。 當我在命令提示符下運行此命令時,我可以很好地接收第一個名稱,但是之后,第二個cin.getline()不會讀取任何輸入。 有什么建議嗎?

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
    char name1[100], name2[100], name3[100];
    int numBat, numHit;
    double avg1, avg2, avg3;

    // Get Average for Player 1
    cout << "What's Your Name? ";
    cin.getline(name1, 100);

    cout << "How many times have you been at bat? ";
    cin >> numBat;

    if(numBat < 0 || numBat > 25)
    {
        cout << "ERROR ::: Number of Times at Bat Cannot Be Less Than 0 or Greater Than 25. Run Program Again." << endl;
        return 0;
    }
    else
    {

        cout << "How many times have you hit the ball? ";
        cin >> numHit;

        if(numHit < 0)
        {
            cout << "ERROR ::: Number Hit Cannot Be Less Than 0. Run Program Again." << endl;
            return 0;
        }
        else
        {
            // Calculate Average for Player 1
            avg1 = numHit / numBat;

            // Get Average for Player 2
            cout << "What's Your Name? ";
            cin.getline(name2, 100);

            cout << "How many times have you been at bat? ";
            cin >> numBat;

            cout << "How many times have you hit the ball? ";
            cin >> numHit;
                  }
         }
}

我認為這是一個緩沖問題。 嘗試在第二條getline之前沖洗cin

cin.clear(); // clear the buffer
cin.sync();

如果那不起作用,請嘗試如下操作:

cin.ignore(256, '\n'); // ignore the endline and char(256)

getline ,您需要使用cout << endl;輸出換行符cout << endl;

使用時

   cin >> numBat;

它不會讀取換行符,因此下一個cin.getline()將讀取並繼續。

采用

cin >> numBat;
cin.ignore(80,'\n');

暫無
暫無

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

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