Comparing Strings to INTS

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Jetboy555
    New Member
    • Nov 2006
    • 6

    Comparing Strings to INTS

    Sample input:

    2000 Georgia Tech 30 Virginia 20
    1999 Virginia 20 Virginia tech

    My Problem is in taking the input in correctly. I take the year in correctly, but i'm having trouble with the names because some of them are two strings long.

    right now i have

    input << year << Winner1 << Winner2 < Score << Loser1 < Loser2 << Score

    where Winner1, Winner2, and Loser1, Loser2, are all strings. The problem is that because they are strings they reading the score if the second word doesn't exist.
    I realize i need some kind if statement comparing my string , but i'm stuck
    there.


    Thanks for any help
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    a simple way is to use peek() to look at the next character in the input stream to see if it is a digit, if so you read an int otherwise a string - sucessive strings can be concatenated, e.g.
    Code:
    // reading int or string using peek() to look at next character
    
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main()
    {
        while(cin.good())
        {
            int num=0;
            string s="";
            if(isdigit(cin.peek()))                 // peek at next character
                {
                cin >> num;                           // numeric read an int
                cout << "number " << num << endl;
                }
             else
                {
                cin >> s;                             // not numeric read a string
                cout << "string " << s << endl;
                }
           }
    }
    you data gives
    number 2000
    string Georgia
    string Tech
    string 30
    string Virginia
    string 20
    string 1999
    string Virginia
    string 20
    string Virginia
    string tech
    string

    Comment

    Working...