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

finding an integer in a string

P: 62
Hello, I've got a problem and would appreciate any help.
I have to count the number of integers in a string like this "1.1 some text. 1.2 some text", where it should return 0, as there are no integers, but I still get 2 on the output.
Here is the code:

Expand|Select|Wrap|Line Numbers
  1. void IntegerNumber()
  2. {
  3.     int NumberOfIntegers = 0;
  4.     string SubString;
  5.     int flag;
  6.  
  7.     while (!file.eof())
  8.     {
  9.         getline(file, SubString, ' ');
  10.         flag = 0;
  11.         for (int i = 0; i < SubString.length(); i++)
  12.         {
  13.             if (SubString[i] >= '0' && SubString[i]<= '9') flag = 1;
  14.             else flag = 0;
  15.         }
  16.         if (flag == 1) ++NumberOfIntegers;
  17.     }
  18.     cout << "The number of Integers = " << NumberOfIntegers << endl; 
  19. }
  20.  
And I also need a second function, which counts the doubles in the same string, could anyone give me a hint what I need to change in this code for that?
Thanks a lot!
Jan 28 '07 #1
Share this Question
Share on Google+
2 Replies


100+
P: 1,646
In your example the 2 integers will be 1 and 1. You need a more sophisticated algorithm to detect the period in the middle. In a normal sentence the period is folowed by a space so you can use this information to detect both an integer and a double.

good luck
Jan 28 '07 #2

P: 62
Thanks a lot for your reply!!!
I now got the idea: In the else statement after the flag goes to 0, I've added one line: break; and it is working now!!! ;))
Jan 28 '07 #3

Post your reply

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