首页 > 解决方案 > 如何停止接受任意数量的输入?

问题描述

我没有特定数量的输入。金额可以是任何东西。所以我必须使用这个循环。但是一旦我完成了如何停止输入呢?

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

使用此循环获取输入,因为我不知道输入的数量。但是一旦我完成输入,我该如何停止循环?

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

}

}

标签: c++while-loopeof

解决方案


取决于您希望输入采用什么形式。如果预期的输入是单行的数字列表,由空格分隔:

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

}

对于更健壮的解决方案,还可以考虑检查输入以查看是否可以将其制成整数。


推荐阅读