在CPP中使用cout的重复输出

问题描述 投票:0回答:1

我试图在程序中读取一行字符串,并且当字符串为"q"时,程序应该会中断,但是我的主要功能有些奇怪的行为。您能为我找到吗?

非常感谢!

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int distance;
    int points[1000][2] = {0};
    string input;

    cout << "Please enter the distance: ";
    cin >> distance;
    cin.clear();

    while (true) {
        cout << "Please enter the coordinates, ";
        cout << "enter \"q\" to exit: ";
        getline(cin, input);
        cin.clear();

        // Finish input
        if (input == "q")
            break;
    }

    return 0;
}

并且终端中的输出是:

Please enter the distance: 5
Please enter the coordinates, enter "q" to exit: Please enter the coordinates, enter "q" to exit:

cout循环中的while似乎已进行了两次。

c++ loops std cin cout
1个回答
1
投票

clear函数无法执行您显然希望它执行的操作。它仅清除流状态标志。

您似乎想要的clear函数可能会忽略第一个输入操作留下的换行符:

ignore

注意,在ignore调用之后,您应该not调用cin >> distance; cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Skip the remainder of the line ,因为ignore函数也会读取换行符。

© www.soinside.com 2019 - 2024. All rights reserved.