C++ 如何将cin转换为向量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8377660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:28:08  来源:igfitidea点击:

How to cin to a vector

c++templatesfunctionvector

提问by Sean

I'm trying to ask the user to enter numbers that are put into a vector, then using a function call to count the numbers, why is this not working? I am only able to count the first number.

我试图让用户输入放入向量中的数字,然后使用函数调用来计算数字,为什么这不起作用?我只能数出第一个数字。

template <typename T>
void write_vector(const vector<T>& V)
{
   cout << "The numbers in the vector are: " << endl;
  for(int i=0; i < V.size(); i++)
    cout << V[i] << " ";
}

int main()
{
  int input;
  vector<int> V;
  cout << "Enter your numbers to be evaluated: " << endl;
  cin >> input;
  V.push_back(input);
  write_vector(V);
  return 0;
}

回答by jsinger

As is, you're only reading in a single integer and pushing it into your vector. Since you probably want to store several integers, you need a loop. E.g., replace

照原样,您只读取一个整数并将其推入您的向量中。由于您可能想要存储多个整数,因此您需要一个循环。例如,替换

cin >> input;
V.push_back(input);

with

while (cin >> input)
    V.push_back(input);

What this does is continually pull in ints from cin for as long as there is input to grab; the loop continues until cin finds EOF or tries to input a non-integer value. The alternative is to use a sentinel value, though this prevents you from actually inputting that value. Ex:

只要有要抓取的输入,它就会不断地从 cin 中提取整数;循环一直持续到 cin 找到 EOF 或尝试输入非整数值。另一种方法是使用标记值,尽管这会阻止您实际输入该值。前任:

while ((cin >> input) && input != 9999)
    V.push_back(input);

will read until you try to input 9999 (or any of the other states that render cin invalid), at which point the loop will terminate.

将一直读取,直到您尝试输入 9999(或使 cin 无效的任何其他状态),此时循环将终止。

回答by Jon Purdy

Other answers would have you disallow a particular number, or tell the user to enter something non-numeric in order to terminate input. Perhaps a better solution is to use std::getline()to read a lineof input, then use std::istringstreamto read all of the numbers from that line into the vector.

其他答案会让您禁止特定数字,或告诉用户输入非数字内容以终止输入。也许更好的解决方案是使用std::getline()读取一行输入,然后使用读取该行中std::istringstream所有数字到向量中。

#include <iostream>
#include <sstream>
#include <vector>

int main(int argc, char** argv) {

    std::string line;
    int number;
    std::vector<int> numbers;

    std::cout << "Enter numbers separated by spaces: ";
    std::getline(std::cin, line);
    std::istringstream stream(line);
    while (stream >> number)
        numbers.push_back(number);

    write_vector(numbers);

}

Also, your write_vector()implementation can be replaced with a more idiomatic call to the std::copy()algorithm to copy the elements to an std::ostream_iteratorto std::cout:

此外,您的write_vector()实现可以替换为对std::copy()算法的更惯用的调用,以将元素复制到std::ostream_iteratorto std::cout

#include <algorithm>
#include <iterator>

template<class T>
void write_vector(const std::vector<T>& vector) {
    std::cout << "Numbers you entered: ";
    std::copy(vector.begin(), vector.end(),
        std::ostream_iterator<T>(std::cout, " "));
    std::cout << '\n';
}

You can also use std::copy()and a couple of handy iterators to get the values into the vector without an explicit loop:

您还可以使用std::copy()和 几个方便的迭代器来将值放入向量中,而无需显式循环:

std::copy(std::istream_iterator<int>(stream),
    std::istream_iterator<int>(),
    std::back_inserter(numbers));

But that's probably overkill.

但这可能是矫枉过正。

回答by Nawaz

You need a loop for that. So do this:

你需要一个循环。所以这样做:

while (cin >> input) //enter any non-integer to end the loop!
{
   V.push_back(input);
}

Or use this idiomatic version:

或者使用这个惯用的版本:

#include <iterator> //for std::istream_iterator 

std::istream_iterator<int> begin(std::cin), end;
std::vector<int> v(begin, end);
write_vector(v);

You could also improve your write_vectoras:

你也可以改进你write_vector的:

 #include <algorithm> //for std::copy

template <typename T>
void write_vector(const vector<T>& v)
{
   cout << "The numbers in the vector are: " << endl;
   std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
}

回答by H_meir

you have 2 options:

你有两个选择:

If you know the size of vector will be (in your case/example it's seems you know it):

如果您知道向量的大小将是(在您的情况/示例中,您似乎知道):

vector<int> V(size)
for(int i =0;i<size;i++){
    cin>>V[i];
 }

if you don't and you can't get it in you'r program flow then:

如果你不这样做并且你不能在你的程序流中得到它,那么:

int helper;
while(cin>>helper){
    V.push_back(helper);
}

回答by Wojciech Migda

One-linerto read a fixedamount of numbers into a vector (C++11):

固定数量的数字读入向量的单行(C++11):

#include <algorithm>
#include <iterator>
#include <iostream>
#include <vector>
#include <cstddef>

int main()
{
    const std::size_t LIMIT{5};
    std::vector<int> collection;

    std::generate_n(std::back_inserter(collection), LIMIT,
        []()
        {
            return *(std::istream_iterator<int>(std::cin));
        }
    );

    return 0;
}

回答by 01d55

You need a second integer.

您需要第二个整数。

int i,n;
vector<int> V;
cout << "Enter the amount of numbers you want to evaluate: ";
cin >> i;
cout << "Enter your numbers to be evaluated: " << endl;
while (V.size() < i && cin >> n){
  V.push_back(n);
}
write_vector(V);
return 0;

回答by Amit Sharma

If you know the size use this

如果您知道尺寸,请使用此

No temporary variable used just to store user input

没有仅用于存储用户输入的临时变量

int main()
{
    cout << "Hello World!\n"; 
    int n;//input size
    cin >> n;
    vector<int>a(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }

//to verify output user input printed below

    for (auto x : a) {
        cout << x << " ";
    }
    return 0;
}

回答by Arslan Ahmad

You can simply do this with the help of for loop
->Ask on runtime from a user (how many inputs he want to enter) and the treat same like arrays.

您可以在for 循环的帮助下简单地执行此操作
-> 在运行时询问用户(他想输入多少个输入),并将其视为数组。

int main() {
        int sizz,input;
        std::vector<int> vc1;

        cout<< "How many Numbers you want to enter : ";
        cin >> sizz;
        cout << "Input Data : " << endl;
        for (int i = 0; i < sizz; i++) {//for taking input form the user
            cin >> input;
            vc1.push_back(input);
        }
        cout << "print data of vector : " << endl;
        for (int i = 0; i < sizz; i++) {
            cout << vc1[i] << endl;
        }
     }

回答by johnathan

cin is delimited on space, so if you try to cin "1 2 3 4 5" into a single integer, your only going to be assigning 1 to the integer, a better option is to wrap your input and push_back in a loop, and have it test for a sentinel value, and on that sentinel value, call your write function. such as

cin 以空格分隔,因此如果您尝试将 cin "1 2 3 4 5" 转换为单个整数,您只会将 1 分配给该整数,更好的选择是将输入和 push_back 包装在一个循环中,并且让它测试一个哨兵值,并在该哨兵值上调用你的写函数。如

int input;
cout << "Enter your numbers to be evaluated, and 10000 to quit: " << endl;
while(input != 10000) {
    cin >> input;
   V.push_back(input);
}
write_vector(V);

回答by shiva Mirjapur

#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
    vector<string>V;
    int num;
    cin>>num;
    string input;
    while (cin>>input && num != 0) //enter any non-integer to end the loop!
{
    //cin>>input;
   V.push_back(input);
   num--;
   if(num==0)
   {
   vector<string>::iterator it;
    for(it=V.begin();it!=V.end();it++)
        cout<<*it<<endl;
   };

}
return 0;

};