如何停止采取任意数量的输入?

问题描述 投票:0回答:2

我没有具体的输入量。这个数量可以是任何东西。所以我必须使用这个循环。但是,一旦我完成了输入,如何停止接受输入?

#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
vector<int>v;

使用这个循环来获取输入,因为我不知道输入的数量。但是我怎么在输入完成后停止循环呢?

while(cin){
cin >> n;
v.push_back(n);

}

}
c++ while-loop eof
2个回答
1
投票

取决于你期望输入的形式。如果期望的输入是一个数字列表,用空格分隔,在一行上。

>>>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;

}

为了更稳健的解决方法,也可以考虑检查输入是否可以被转换成ints.


0
投票

我相信这不会是代码本身的问题,而更多的是在格式化输入时的问题。你可以把所有的输入都放到一个文本文件中,然后在命令终端把它作为一个参数传给可执行文件,就像这样。executable_name < file_name. 另外,通过一点重构,你可以将你的 while 循环重构为 so。

while(cin >> n){
    v.push_back(n);
}

有了这个 while 循环,你现在可以在输入文件的结尾放置一个你选择的转义字符 这样当检测到一个非数字字符时 while 循环就会中断

© www.soinside.com 2019 - 2024. All rights reserved.