How to user input the array elements in c++ in one line

19,287

Solution 1

You can use this simple example:

#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


or, if you want to have it more generic and nicely enclosed within a function returning 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

Solution 2

Read in all the values into one string, then use a tokenizer to separate out the individual values.

How do I tokenize a string in C++?

Solution 3

The above answers are very good for an arbitrary number of inputs, but if you allready know how many numbers will be put, you could do it like:

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

But please note that this method does not do any check if the numbers are put properly, so if there are for example letters or special characters in the input, you might get unexpected behavior.

Share:
19,287
Manoj Dhiman
Author by

Manoj Dhiman

I am a php proggrammer

Updated on June 26, 2022

Comments

  • Manoj Dhiman
    Manoj Dhiman almost 2 years

    I am new to c++ , Basically I belong to PHP . So I am trying to write a program just for practice, to sort an array . I have successfully created the program with static array value that is

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

    its output is ok . But I want that the elements should input from user with space separated or , separated . So i have tried this

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

    it is not throwing an error while compiling. But op is not as required . It is

    Enter , seperated values :20,56,67,45

    myvector contains: 0 0 0 0 50 3276800 4196784 4196784

    ------------------ (program exited with code: 0) Press return to continue

    • molbdnilo
      molbdnilo over 8 years
      values is one char, so your array has exactly one element. You should use std::vector<int> and push_back. (Examples are all over the internet.)
    • user877329
      user877329 over 8 years
      You do not need a special class for sorting ints since it already supports operator<.
  • molbdnilo
    molbdnilo over 8 years
    Please read this question and its answers.
  • PiotrSliwa
    PiotrSliwa over 8 years
    @molbdnilo Good observation, thanks. I've updated the answer.
  • Admin
    Admin over 2 years
    Please provide additional details in your answer. As it's currently written, it's hard to understand your solution.
  •  MUKUL RANA
    MUKUL RANA over 2 years
    i think i have give details in comments ,actually here we are iterating through the string whenver we are encountering with '-' minus sign it means the next char should be treated as negative charcter when we convert this to integer array FOR EX: 12-3 is given here at index '3' we have - this and next index is the number 3 but we want -3 as integer so i in code so iam just making 4th index negative i,e the next index after - this sign in string we have given