C++ 从控制台读取整数数组
c++ read integer array from console
所以我在从控制台读取一些数字时一直试图摆脱无限循环。这是读取部分代码:
vector<int> all;
string input;
while (getline(cin, input)) {
int number;
stringstream ss(input);
while (ss >> number) {
all.push_back(number);
}
}
我也试过这个:
vector<int> all;
while (cin >> number) {
all.push_back(number);
}
解决此问题的一种快速方法是在从控制台输入空行时中断外部循环:
while (getline(cin, input))
{
if (input == "")
break;
...
}
注意:某些实现在 getline 中的行尾返回一个回车符,它只条带化新行(换行符(http://www.cplusplus.com/reference/string/string/getline/
如前所述,这是一种非常简单快捷的退出无限循环的方法,从用户的角度来看,他/她可以输入由空格、制表符、Enter 或任何组合分隔的数字,您的向量将被填充,直到用户输入空行。
您的代码将如下所示:
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
vector<int> all;
string input;
while (getline(cin, input)) {
if (input == "")
break;
int number;
stringstream ss(input);
while (ss >> number) {
all.push_back(number);
}
}
// Here the vector "all" has any numbers entered by user
return 0;
}
相关文章:
- 从二进制文件中读取整数数组
- 新的整数数组向右移动?
- C++ 中的二维整数数组,每行中的元素数量不均匀
- 给定一个整数数组,需要在Max_Heap上运行操作。得到错误"segmentation fault",有什么想法吗?(C++)
- 为什么在我的 main 函数中声明整数后我的整数数组中会出现错误?
- 在 C++ 中将整数数组转换为位集表示形式的最佳方法?
- 从两个 4x64 位整数数组中获取取模
- 字符到整数数组
- 从函数参数 [C++] 复制整数数组
- 指向整数数组和打印总和的指针
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 线程安全整数数组?
- 整数数组中最长的回文
- 在大整数数组中查找子数组
- 查找整数数组中最接近的数字
- 创建<int>对整数数组指针的矢量引用 (C++)
- 整数指针数组的元素是否可以指向整数数组?
- 如何将整数数组相乘得到一个数字?
- 当 map 是一个整数数组并且由 operator[] 创建时,它是否初始化其映射类型
- 将文本文件读入整数数组