簡體   English   中英

為什么我的輸入在這個 C++ 程序中如此混亂?

[英]Why is my input so messed up in this C++ program?

我正在嘗試為 Linux 制作一個命令行郵件應用程序(盡管我正在 Xcode 上開發,因為 VM 為我的計算機使用了大量電源)。 我在主菜單中有兩個選項(用戶輸入一個數字來選擇)。 無論是簡單的罐頭還是get line(can,stringName),我在每次輸入后都使用它:

void clearCin() {
    cin.clear();
    cin.ignore(INT_MAX, '\n');
}

這就是為什么我很困惑我的輸入會出現各種奇怪的行為。 這是我的代碼和示例 output (結尾 function 只是一個成本 << endl; 的 for 循環):

代碼

bool stdEmail() {

    string to, cc, bcc, subject, message;

    cout << "When entering email addresses, seperate multiple email addresses with a space";
    endl(2);

    cout << "To: ";
    getline(cin, to);
    clearCin();

    cout << "cc: ";
    getline(cin, cc);
    clearCin();

    cout << "bcc: ";
    getline(cin, bcc);
    clearCin();
    endl(1);

    cout << "Subject: ";
    getline(cin, subject);
    clearCin();
    endl(1);

    cout << "Now enter your message, when you're finished, type a period on a new line";
    endl(2);

    ofstream file;
    file.open("newMessage.txt", fstream::trunc);

    bool repeat = true;

    while (repeat) {
        getline(cin, message);
        clearCin();
        if (message == ".") {
            repeat = false;
        } else {
            file << message << endl;
        }
    }

    file.close();
    return true;
}

Output

--------------------------------------------------
Welcome to mark's Multi-Mail program

Main menu:
--------------------------------------------------
1. Send personalized emails to multiple recipients
2. Send a standard email
3. Exit the program
--------------------------------------------------
2

When entering email addresses, seperate multiple email addresses with a space

To: one@example.com two@example.com

cc: three@example.com

bcc: 


Subject: Thanks for your help!


Now enter your message, when you're finished, type a period on a new line

Here is a sample message
.

Now I am trying to get it out of taking the message which should have happened when I typed a .


.


Program ending Have a Nice Day

Program ended with exit code: 0

以下是 newMessage.txt 中顯示的內容:

這是一個示例消息

cin.ignore(INT_MAX, '\n'); 丟棄換行符,getline 在讀取換行符時完成,因此您必須在輸入消息后按兩次回車鍵才能讀取它,並且在輸入“。”后必須按兩次回車鍵。 結束你的循環。

暫無
暫無

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

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