Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > strtok help

Reply
Thread Tools

strtok help

 
 
Glen
Guest
Posts: n/a
 
      08-10-2005
#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


 
Reply With Quote
 
 
 
 
rusttree@gmail.com
Guest
Posts: n/a
 
      08-10-2005
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";

}

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Help with strtok manochavishal@gmail.com C Programming 8 03-16-2006 02:57 PM
Help With strtok manochavishal@gmail.com C Programming 2 03-14-2006 09:44 AM
strtok ( ) help ern C Programming 13 01-25-2006 01:58 AM
strtok() and std::string Alex Vinokur C++ 6 04-14-2005 01:40 PM
Problems with strtok() returning one too many tokens... Adam Balgach C++ 2 11-28-2004 01:12 AM



Advertisments