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
You can use this simple example:
Live demo
or, if you want to have it more generic and nicely enclosed within a function returning
std::vector
:Live demo
Let's see what you wrote:
what you need is:
If you want comma separated input you'll need to parse the comma as a single character in addition to the integer values.
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++?
What you are doing
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
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 thedefault
case: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:
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.