Manoj Dhiman
Manoj Dhiman

Reputation: 5166

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

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

Upvotes: 3

Views: 23025

Answers (6)

 MUKUL RANA
MUKUL RANA

Reputation: 21

#include <iostream>
#include <string>
#include <sstream>
#include <string.h>
using namespace std;
// THIS CODE IS TO GIVE ARRAY IN ONE LINE AND OF DESIRED LENGHT ALSO WITH NEGATIVE NUMBERS
// You can also do it by using ASCII but we Are using library name
//   <sstream>   to convert string charters to numbers
//O(n) time complexity
int main()
{
/*
// INPUT
// 7 array length
// 34-56-789   // without space b/w them */
    int N;
    cout << "Enter the size of the array " << endl;
    cin >> N;
    cout << "INPUT Without giving space b/w " << endl;
    string strx;
    cin >> strx;
    int X[N]; // array to store num
    int p = 0;
    // NOTE USE HERE STRX.LENGHT() becouse we have to go through the whole string
    for (int i = 0; i < strx.length(); i++)
    {   // we have declare tempx to store a particular character
        // one time
        string tempx;
        tempx = strx[i];
        stringstream strtointx(tempx);
        //  this is the syntax to convert char to int using <sstream>
        if (strx[i] == '-')
        {
/*
 The tricky point is when you give string as 1-23
 here - and 2 are the separte characters so we are not
getting -2 as number but - and 2 so what we do is 
we chek for '-' sign as the character next to it 
will be treated as negative number 
 */
        tempx = strx[i + 1];
// by assigning strx[i+1] to tempx so that we can getting the which should be treated as negative number
        stringstream strtointx(tempx);
// still it is a charter type now again using library
// convert it to int type
            strtointx >> X[p];
            X[p] = -X[p];
// now make that number to negative ones as we want it to be negative
            i++;
// inside this if i++ will help you to skip the next charcter of string
// so you can get desired output
        } 
        // now for all the positive ones to int type
        else{   strtointx >> X[p];     }
         p++; // finally increment p by 1 outside if and else block
        }
    // loop ends now get your desired output
    cout<<"OUTPUT "<<endl;
    for (int i = 0; i < N; i++)
    {
        cout << X[i] << " ";
    }
    cout<<endl;
    cout<<"CODE BY MUKUL RANA NIT SGR Bch(2020)";
    return 0;
}


// OUTPUT
/*
Enter the size of the array 
7
INPUT Without giving space b/w 
34-56-789
OUTPUT 
3 4 -5 6 -7 8 9
CODE BY MUKUL RANA NIT SGR Bch(2020)
PS C:\Users\user\Desktop\study c++> 
*/


// CAUTION :
/*
1) do not give input with spaces 
****  if you do then first you have to change /chek the code for spaces indexes also ***
2)do not give charates as 56-89@#13 as you want here only numbers 
3) this only for integer if you want to float or double you have to do some changes here 
 because charters index and length would be difeerent in string.
*/

Upvotes: 0

user877329
user877329

Reputation: 6200

What you are doing

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

In the language char works as an 8-bit integer. Through function overloading, different behavior can be implemented. Read about static polymorphism for more details how it works.

What you need to do

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

You should put this in a separate function. With this skeleton, you can implement a more fancy syntax by adding more cases, but then you need something else than a std::vector<int> to put things into. You can (should?) also add error checking in the default case:

         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();
             }

Upvotes: 0

DrDonut
DrDonut

Reputation: 904

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.

Upvotes: 1

psliwa
psliwa

Reputation: 1092

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

Upvotes: 5

BeyelerStudios
BeyelerStudios

Reputation: 4283

Let's see what you wrote:

int main () {
    char values;
    std::cout << "Enter , seperated values :";
    std::cin >> values; // read a single character
    int myints[] = {values}; // create a static array of size 1 containing the single character converted to an int

    /* other function same */
}

what you need is:

#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 */
}

If you want comma separated input you'll need to parse the comma as a single character in addition to the integer values.

Upvotes: 0

ravenspoint
ravenspoint

Reputation: 20457

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++?

Upvotes: 1

Related Questions