How to input a telephone number and use function strtok to extract?

This is a discussion on How to input a telephone number and use function strtok to extract? within the C++ Programming forums, part of the General Programming Boards category; output should like that: input #: (909)869-2511 area: (909) exchange: 869 ext.: 2511 #: (909)869-2511 Code: #include <iostream> #include <iomanip> ...

  1. #1
    Registered User
    Join Date
    Jun 2009
    Posts
    4

    Unhappy How to input a telephone number and use function strtok to extract?

    output should like that:

    input #: (909)869-2511
    area: (909)
    exchange: 869
    ext.: 2511
    #: (909)869-2511

    Code:
    #include <iostream>
    #include <iomanip>
    #include <cstring>
    using namespace std;
    
    int main()
    {
    char sentence[32];
    char *tokenPtr;
    tokenPtr = &sentence;
    
    cout << "Input Telephone No.: " ;
    cin >> sentence;
    tokenPtr = strtok( sentence, " " );
    
    while ( tokenPtr != NULL )
    {
    cout << tokenPtr << '\n';
    tokenPtr = strtok( NULL, " " );
    }
    return 0;
    }

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    You need to tell strtok where things stop in order for it to work properly.

    On the other hand, you probably shouldn't use strtok since that will erase the token-splitting characters (i.e., ')' and '-'). You can use strchr to search for specific characters in a string.

    Even better, you could ditch C strings and use C++ strings.

  3. #3
    Registered User
    Join Date
    Jun 2009
    Posts
    4
    this is my first time to use it and the book doesn't tell
    how to input string and cout like the very top.
    can you help me fix my code? cause I can't find the errors.

  4. #4
    Banned ಠ_ಠ's Avatar
    Join Date
    Mar 2009
    Posts
    687
    imo this would be a good time to use scanf
    ╔╗╔══╦╗
    ║║║╔╗║║
    ║╚╣╚╝║╚╗
    ╚═╩══╩═╝

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21