使用 cin 的返回值在 C++ 中输入未知数量的输入


有时候,我们需要在我们的程序中输入变量数目的输入。在这个程序中,我们将看到如何使用 cin 来输入变量数目的输入。

简单的解决方案是运行一个循环,当按下一个特定的值时停止。另一个想法是使用 cin >> 输入。当值是非数字时,这会返回 false。

示例

#include <iostream>
using namespace std;
main() {
   int input;
   int n = 0;
   cout << "Enter numbers. (To stop enter any character): ";
   while (cin >> input)
   n++;
   cout << "\nTotal number of inputs entered: " << n;
}

输出

Enter numbers. (To stop enter any character): 
5
6
7
2
6
5
j
Total number of inputs entered: 6

更新于:30-Jul-2019

1K+ 浏览

开启你的 职业生涯

完成课程,获得认证

开始
广告
© . All rights reserved.