Recently I've been helped on making a program which counts numbers found in a string.
A little problem though..I'm stuck on how to enable user to Input the string he wants.
Please help
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
stringstream in( "More like cat 7 dog 42 9000" );
string word;
int counter = 0;
while ( in >> word )
{
if ( word.find_first_not_of( "0123456789" ) == string::npos && stoi( word ) < 1000 ) counter++;
}
cout << "There are " << counter << " numbers less than 1000\n";
}
This prints 1 when I enter a string < 1000, and 0 when enter a string with non-digits or digits >= 1000.
Enter string: 999
1
Enter string: a123
0
Enter string: 1234
0
As someone in the other thread on this topic noted, more work is needed if you want to parse negative numbers in this manner (check if first digit is '-').
Sorry,you recently helped me on my program to count numbers found in string.
But now I want to update the program to ask the user how many strings he wants to Input vertically.
Then that will be the limit of the strings which should be entered.
Example
Output:Enter number of strings:
Input:7
Output:Enter strings:
Input:
More
Like
Cat
7
dog
42
9000
Output:There are 2 numbers less than 1000.
Sorry for disturbing and thanks.
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
cout << "Enter a succession of words, one per line. Finish with a blank line:\n";
string word;
int counter = 0;
while ( getline( cin, word ) && !word.empty() )
{
if ( word.find_first_not_of( "0123456789" ) == string::npos && stoi( word ) < 1000 ) counter++;
}
cout << "There are " << counter << " numbers less than 1000\n";
}
Enter a succession of words, one per line. Finish with a blank line:
More
like
cat
7
dog
42
9000
There are 2 numbers less than 1000