-2

I am trying to break a string with space delimiter but it didn't work,where as with "," it works fine. Can anyone help me with this. Following is the piece of my code.

char x[150];
int a[150];
cin >> x;
int i = 0;
char * pch;

pch = strtok(x, " ");
while (pch != NULL)
{
    a[i] = atoi(pch);
    cout<< a[i]<<"\t";
    pch = strtok (NULL, " ");
    i++;
}

input: 12 23 50

output: 12

output with comma separator:12 23 50

1 Answers1

1

Your problem is that cin >> x; only gives you the input until the first space.

So even if you type 12 23 50 you'll only get 12

The rest of the input remains in cin. So if you did cin >> x three times you would get 12 and 23 and 50

To read the whole line use std::getline instead. See Reading a full line of input

But (as suggested in several comments) use of strok is not good. Also you should use std::string instead of the char-array.

For splitting a string, see the link provided by Dieter Lucking Split a string in C++?.

Community
  • 1
  • 1
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63