【问题标题】:How to stop taking an arbitrary number of inputs?如何停止接受任意数量的输入?
【发布时间】:2020-05-02 00:27:03
【问题描述】:

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

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

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

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

}

}

【问题讨论】:

  • 您设置了一个退出条件来停止循环。该代码应该如何知道您何时完成输入而没有告诉它停止循环的条件?
  • 在 Windows 上,您可以使用 CTRL+Z 终止控制台输入。
  • #include&lt;bits/stdc++.h&gt; 是非标准的,包含很多你不需要的东西。您应该为所使用的类型包含正确的标题。
  • @BessieTheCow:你真的认为这是在 C++ 程序中退出 while 循环的正确方法吗?
  • @KenWhite - 如果一个程序正在从标准输入读取,并且用户正在从控制台或控制台窗口运行该程序,并且操作系统是 Windows,那么用户发出结束信号的一种方式输入是使用 CTRL-Z。标准 C++ 没有为用户交互提供丰富的选项(例如,不支持 GUI),所以这些东西大部分都在程序的控制之外。

标签: c++ while-loop eof


【解决方案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;

}

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

【讨论】:

    【解决方案2】:

    我相信这不是代码本身的问题,而是在格式化输入时更多的问题。您可以将所有输入放入一个文本文件中,并将其作为参数传递给命令终端中的可执行文件,如下所示:executable_name &lt; file_name。此外,通过一些重构,您可以重新格式化 你的while循环是这样的:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-23
      • 1970-01-01
      • 1970-01-01
      • 2014-03-07
      • 2018-11-04
      • 2023-03-07
      • 2016-02-22
      • 2019-04-11
      相关资源
      最近更新 更多