strtok help

Discussion in 'C++' started by Glen, Aug 10, 2005.

  1. Glen

    Glen Guest

    #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
     
    Glen, Aug 10, 2005
    #1
    1. Advertising

  2. Glen

    Guest

    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";

    }
     
    , Aug 10, 2005
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Adam Balgach
    Replies:
    2
    Views:
    600
    news-east
    Nov 28, 2004
  2. Alex Vinokur

    strtok() and std::string

    Alex Vinokur, Apr 14, 2005, in forum: C++
    Replies:
    6
    Views:
    4,972
    Pete Becker
    Apr 14, 2005
  3. ern

    strtok ( ) help

    ern, Jan 20, 2006, in forum: C Programming
    Replies:
    13
    Views:
    850
  4. Help with strtok

    , Mar 14, 2006, in forum: C Programming
    Replies:
    8
    Views:
    390
    CBFalconer
    Mar 16, 2006
  5. Help With strtok

    , Mar 14, 2006, in forum: C Programming
    Replies:
    2
    Views:
    452
Loading...

Share This Page