简体   繁体   English

C ++:如何在控制台窗口中显示结果

[英]C++: how to show the result in the console window

#include <iostream>
using namespace std;

int main()
{
    int sum = 0;

    cout << "Please input a series of integers and any number of spaces: ";

    int i;
    while( cin >> i )
    {
        sum += i;
        while( cin.peek() == ' ' ) // isolate spaces
        {
            cin.get();
        }

        if( cin.peek() == '\n') // when press "enter"
        {
            break; // get out of loop
        }
    }

    cout << "The result is: " << sum << endl;
    cin.get();
    return 0;

}

Above is my code. 以上是我的代码。 I try to use cin.get() to show the result in the console window, but it does not work. 我尝试使用cin.get()在控制台窗口中显示结果,但是它不起作用。 It reveals a window flash. 它显示了一个窗口闪烁。

You peek to see if there is a newline in the input. 偷看一下输入中是否有换行符。 If it is you leave it in the input buffer and break out of the loop, where your cin.get() call will read that newline. 如果是这样,则将其保留在输入缓冲区中并退出循环,您的cin.get()调用将读取该换行符。


If you only want to read a single line, then I suggest you use std::getline to read the line, put it into an std::istringstream and read the numbers from that stream. 如果您只想读取一行,那么我建议您使用std::getline读取该行,将其放入std::istringstream并从该流中读取数字。

Also note that when reading numbers using >> , leading white-space is read and discarded so you don't have to check for that. 另请注意,使用>>读取数字时,将读取并丢弃前导空格,因此您无需进行检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM