如何在C++中用户在一行中输入数组元素

Man*_*mar 3 c++ arrays iostream

我是c++新手,基本上属于PHP。所以我试图编写一个程序只是为了练习,对数组进行排序。我已经成功创建了具有静态数组值的程序,即

// sort algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::sort
#include <vector>       // std::vector


bool myfunction (int i,int j) { return (i<j); }

struct myclass { bool operator() (int i,int j) { return (i<j);} } myobject;

int main () {
   int myints[] = {55,82,12,450,69,80,93,33};
  std::vector<int> myvector (myints, myints+8);               

  // using default comparison (operator <):
  std::sort (myvector.begin(), myvector.begin()+4);           

  // using function as comp
  std::sort (myvector.begin()+4, myvector.end(), myfunction); 

  // using object as comp
  std::sort (myvector.begin(), myvector.end(), myobject);     

  // print out content:
  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
    std::cout << '\n';

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

它的输出是好的。但我希望元素应该从用户输入space分离或,分离。所以我尝试过这个

int main () {
    char values;
    std::cout << "Enter , seperated values :";
    std::cin >> values;
  int myints[] = {values};


  /* other function same */
}
Run Code Online (Sandbox Code Playgroud)

编译时它不会抛出错误。但op不符合要求。这是

输入 ,分隔值:20,56,67,45

myvector 包含: 0 0 0 0 50 3276800 4196784 4196784

------------------(程序退出,代码:0)按回车键继续

Pio*_*iwa 5

您可以使用这个简单的示例:

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>

using namespace std;

int main()
{
    stringstream ss;
    string str;
    getline(cin, str);
    replace( str.begin(), str.end(), ',', ' ');
    ss << str;

    int x = 0;
    while (ss >> x)
    {
        cout << x << endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

现场演示


或者,如果您想让它更通用并很好地包含在返回的函数中std::vector

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <vector>

using namespace std;

template <typename T>
vector<T> getSeparatedValuesFromUser(char separator = ',')
{
    stringstream ss;
    string str;
    getline(cin, str);
    replace(str.begin(), str.end(), separator, ' ');
    ss << str;

    T value{0};
    vector<T> values;
    while (ss >> value)
    {
        values.push_back(value);
    }

    return values;
}

int main()
{
    cout << "Enter , seperated values: ";
    auto values = getSeparatedValuesFromUser<int>();

    //display values
    cout << "Read values: " << endl;
    for (auto v : values)
    {
        cout << v << endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

现场演示

  • 请阅读[这个问题](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong)及其答案。 (2认同)