### Thread: need help with manipulating user input

1. No Profile Picture
Lii
Junior Member
Devshed Newbie (0 - 499 posts)

Join Date
Oct 2002
Location
London
Posts
2
Rep Power
0

#### need help with manipulating user input

Suppose a user enters this

cin >> 23,4545,576,43,4

Is there a way I can capture the input and split it into the individual numbers and put them in an integer array in C++. I know there is getline() but it does not allow you to keep the elements as integers. Help will be greatly appreciated.
2. You know you can always use atol() or atoi() to convert a character to a long or integer values.
3. Are there always going to be a fixed number of elements in the input?
4. No Profile Picture
Lii
Junior Member
Devshed Newbie (0 - 499 posts)

Join Date
Oct 2002
Location
London
Posts
2
Rep Power
0
yeah, the user always specifies how many elements they are going to enter.

Thanks Onslaught those functions will come in handy!! :o)
5. You could then possibly use cin in a loop and use a char field to extract the commas out of the way, something like this:
Code:
```#include <iostream>
int main(void) {
int nCount, i;
cout << "Enter number of elements: ";
cin >> nCount;

int *nElems = new int[nCount];
char cDummy;

cout << "Enter elements separated by commas below\n";
for (i=0; i < nCount-1; i++)
cin >> nElems[i] >> cDummy;
cin >> nElems[nCount - 1];

// Now print out the numbers entered
for (i = 0; i < nCount; i++)
cout << i << " => " << nElems[i] << "\n";

// clean up
delete [] nElems;
return 0;
}```
Hope this helps!
6. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Oct 2002
Location
Flint, MI
Posts
328
Rep Power
16
Here's a slightly more elegant solution:

Code:
```int* digit;
int digitno;
string userinput;

cout << "Enter your number: ";
cin >> userinput;

digit = (int*)calloc(userinput.length() + 1, sizeof(int));

digitno=0;
for(int i=0; i < userinput.length(); i++) {
if (isdigit(userinput[i]))
digit[digitno++] = atoi(userinput[i]);```
That way the user doesn't need to know how many digits ahead of time.
7. ClayDowling, the code you've presented won't quite work because atoi works on const char *, not char. So atoi(userinput[i]) won't work. Also it appears that your code is attempting to put each digit in a separate element of the array, which wasn't the original requirement. Interesting approach though :)
8. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Oct 2002
Location
Flint, MI
Posts
328
Rep Power
16
Scorpion, thanks for the heads up. Compiler would have caught that in time. So we'll change the last line of the code a bit:

Code:
`digit[digitno++] = userinput[i] - '0';`
Last edited by ClayDowling; October 31st, 2002 at 02:42 PM.
9. Actually I think it was individual numbers rather than individual digits, with the numbers being separated by commas on the input line.