c++ - 如何停止接受任意数量的输入?
问题描述
我没有特定数量的输入。金额可以是任何东西。所以我必须使用这个循环。但是一旦我完成了如何停止输入呢?
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
vector<int>v;
使用此循环获取输入,因为我不知道输入的数量。但是一旦我完成输入,我该如何停止循环?
while(cin){
cin >> n;
v.push_back(n);
}
}
解决方案
取决于您希望输入采用什么形式。如果预期的输入是单行的数字列表,由空格分隔:
>>>1 2 3 4 5 6
这很容易解决:
#include<vector>
#include<string>
#include<iostream>
#include<sstream>
int main(){
std::vector<int> v; //default construct int vector
//read in line of input into "buffer" string variable
std::string buffer;
std::getline(std::cin, buffer);
//stream line of input into a stringstream
std::stringstream ss;
ss << buffer;
//push space-delimited ints into vector
int n;
while(ss >> n){
v.push_back(n);
}
//do stuff with v here (presumably)
return 0;
}
但是,如果预期的输入是一个数字列表,由新行分隔:
>>>1
2
3
4
5
6
您必须决定退出条件,这将告诉程序何时停止接受输入。这可以采用一个单词的形式,告诉程序停止。例如:
>>>1
2
3
4
5
6
STOP
可以使用此类输入的程序:
#include<vector>
#include<string>
#include<iostream>
#include<sstream>
int main(){
std::vector<int> v; //default construct int vector
const std::string exitPhrase = "STOP"; //initialise exit phrase
//read in input into "buffer" string variable. If most recent input
// matches the exit phrase, break out of loop
std::string buffer;
while(std::cin >> buffer){
if(buffer == exitPhrase) break; //check if exit phrase matches
//otherwise convert input into int and push into vector
std::stringstream ss;
ss << buffer;
int n;
ss >> n;
v.push_back(n);
}
//do stuff with v here (again, presumably)
return 0;
}
对于更健壮的解决方案,还可以考虑检查输入以查看是否可以将其制成整数。
推荐阅读
- python-3.x - 仅通过用户名获取实体后,我可以通过 ID 获取实体。它是一个错误吗?来自外壳的视频
- java - Spring MessageSource 不使用参数
- python-3.x - 关于迭代和优化的问题
- ios - 在 iOS 12 中,当 UICollectionView 是使用具有约束的 Self Sizing 单元格创建时,重新加载布局时高度错误,直到我滚动
- html - 在一个框架中对齐文本和图像需要在图像结束后自动调整图像下方的文本吗?
- vba - 使用 wdFormatDocument 格式保存文档后关闭文档
- angular - 对于来自解析器的数组,无法读取未定义的属性长度
- empirical-lang - 为什么“asof”连接不能既是“最近的”又是“严格的”?
- quarkus - Quarkus Resteasy JSON-B 将列表反序列化为 HashMap 而不是 List
- c# - Task.Delay 或 Thread.Sleep 在同步方法中暂停执行