strtok help

G

Glen

#include <iostream>
#include <string>
using namespace std;
int main(void)
{
/*char test[]="I Glen 21\0";*/
char* choice;
char* number;
char* title;
char test[100];
cin>>test;
choice=strtok(test," ");
title=strtok(NULL," ");
number=strtok(NULL," ");
cout<<choice<<"\n";
cout<<title<<"\n";
cout<<number<<"\n";

}

Why does the program not give the correct output when I use cin I only get
I\n and that all but when I use the hard coded one I get I\nGlen\n21\n

Thank-you
 
R

rusttree

cin will only save string inputs up until a space is found. So when
you typed "I Glen 21" at the prompt, it gave up after finding the first
space between "I" and "Glen". The value of test was set to just "I"
and consequently your strtok statements appeared to fail.

One solution is to replace your cin with cin.getline. Your program
would look like this instead:

#include <iostream>
#include <string>
using namespace std;
int main(void)
{
//char test[]="I Glen 21\0";
char* choice;
char* number;
char* title;
char test[100];
cin.getline(test, 100);
choice=strtok(test," ");
title=strtok(NULL," ");
number=strtok(NULL," ");
cout<<choice<<"\n";
cout<<title<<"\n";
cout<<number<<"\n";

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top