By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,305 Members | 1,614 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,305 IT Pros & Developers. It's quick & easy.

Comparing Strings to INTS

P: 6
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
Nov 6 '06 #1
Share this Question
Share on Google+
1 Reply


Expert 100+
P: 1,510
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.
Expand|Select|Wrap|Line Numbers
  1. // reading int or string using peek() to look at next character
  2.  
  3. #include <iostream>
  4. #include <string>
  5. using namespace std;
  6.  
  7. int main()
  8. {
  9.     while(cin.good())
  10.     {
  11.         int num=0;
  12.         string s="";
  13.         if(isdigit(cin.peek()))                 // peek at next character
  14.             {
  15.             cin >> num;                           // numeric read an int
  16.             cout << "number " << num << endl;
  17.             }
  18.          else
  19.             {
  20.             cin >> s;                             // not numeric read a string
  21.             cout << "string " << s << endl;
  22.             }
  23.        }
  24. }
  25.  
  26.  
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
Nov 6 '06 #2

Post your reply

Sign in to post your reply or Sign up for a free account.