c++ - 在 C++ 中用 cin 读取同一行中的多个整数
问题描述
我从用户那里读取整数时遇到问题。我可以使用
int a, b, c;
cin >> a >> b >> c;
但我不知道用户会引入多少整数。我试过这个:
int n;
cin >> n; //Number of numbers
int arrayNumbers[n];
for(int i=0;i<n;i++){
cin>>arrayNumbers[i]
}
用户的输入将是: 1 2 3 我的意思是,在同一行。使用我以前的代码,它只得到第一个数字,而不是其余的。
我怎么能做到?
解决方案
首先使用 std::getline() 将整行读入字符串。然后从输入字符串创建一个字符串流。最后使用 istream_iterator 迭代各个令牌。请注意,此方法将在第一个不是整数的输入处失败。例如,如果使用输入:“1 2 ab 3”,那么您的向量将包含 {1,2}。
int main() {
std::string str;
//read whole line into str
std::getline(std::cin, str);
std::stringstream ss(str);
//create a istream_iterator from the stringstream
// Note the <int> because you want to read them
//as integers. If you want them as strings use <std::string>
auto start = std::istream_iterator<int>{ ss };
//create an empty istream_iterator to denote the end
auto end= std::istream_iterator<int>{};
//create a vector from the range: start->end
std::vector<int> input(start, end);
}
推荐阅读
- flutter - Flutter 提升 CustomPainter 动画性能
- php - PHPUnit 给出错误:目标 [Illuminate\Contracts\View\Factory] 不可实例化
- python - 如何从鼠标移动中生成真正的随机数?
- python - Keras 如何在级联中计算 2d 卷积
- python - plot(): subplots 的参数有什么作用?
- mysql - mysql。更改 GROUP BY DAY 查询的日期格式输出
- r - 如何使用 lapply 来调整环境中的对象大小?
- swift - GitHub Swift Actions 是否支持自动配置更新?
- json - 如何使用带有嵌套参数的 multipartFormData 上传 doc/img?
- c++ - 解决“ld: library not found for -ltensorflow_framework.2.3.0”