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

时间:2015-09-07 13:42:00

标签: 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;
}

它的输出没问题。但我希望元素应该从space分隔或,分隔的用户输入。所以我试过这个

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


  /* other function same */
}

编译时不会抛出错误。但是op并不是必需的。它是

  

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

     

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

     

------------------(程序退出代码:0)按返回继续

5 个答案:

答案 0 :(得分:3)

您可以使用以下简单示例:

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

Live demo

或者,如果你想让它更通用并且很好地包含在返回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;
    }
}

Live demo

答案 1 :(得分:1)

将所有值读入一个字符串,然后使用标记生成器分离各个值。

How do I tokenize a string in C++?

答案 2 :(得分:1)

以上答案非常适合任意数量的输入,但如果您已经知道将放入多少个数字,您可以这样做:

int[5] intList;
std::cin >> intList[0] >> intList[1] >> intList[2] >> intList[3] >> intList[4]

但请注意,此方法不会检查数字是否正确放置,因此如果输入中有字母或特殊字符,则可能会出现意外行为。

答案 3 :(得分:0)

让我们看看你写的是什么:

#include <sstream>
#include <string>

...

int main () {
    std::cout << "Enter space seperated values :";
    std::vector<int> myvector;
    std::string line;
    std::getline(std::cin, line); // read characters until end of line into the string
    std::istringstream iss(line); // creates an input string stream to parse the line
    while(iss >> value) // so long as values can be parsed
        myvector.push_back(value); // append the parsed value to the vector

    /* other function same */
}

你需要的是:

$.post("your_php_file_url.php",
    {
        card_no: "1", 
        card_name: "wwwgdefonru",  
        img_id: 1, 
        img_thumb: "albums/070915_E239/thumbs/001_wwwgdefonru.jpg", 
        img_hires: "albums/070915_E239/thumbs_hires/001_wwwgdefonru.jpg"
    },
    function(data, status){
        alert("Response Message" + data + "\nResponse Status: " + status);
    });

如果您想要逗号分隔输入,除了整数值之外,您还需要将逗号解析为单个字符。

答案 4 :(得分:0)

你在做什么

int main () {
    char values; //Declare space for one character
    std::cout << "Enter , seperated values :"; //Ask user to enter a value
    std::cin >> values; //Read into values (one value only)
  int myints[] = {values}; // assign the first element to the ASCII code of whatever user typed.


  /* other function same */
}

语言char用作8位整数。通过函数重载,可以实现不同的行为。阅读有关静态多态性的更多详细信息。

你需要做什么

std::vector<int> values;
char ch_in;
std::string temp;
while(cin.get(ch_in)) {
    switch(ch_in) {
         case ',':
         case ' ': //Fall through
             values.push_back(atoi(temp.c_str()); //include cstdlib for atoi
             temp.clear();
             break;
         default:
             temp+=ch_in;
    }
}

你应该把它放在一个单独的功能中。使用此框架,您可以通过添加更多案例来实现更精细的语法,但是除了std::vector<int>之外,还需要其他东西来放置内容。您可以(应该?)在default案例中添加错误检查:

         default:
             if( (ch_in>='0' && ch_in<='9') 
                 || (temp.size()==0 && ch_in=='-') ) {
                 temp+=ch_in;
             }
             else {
                 cerr<<ch_in<<" is an illegal character here."
                 temp.clear();
             }