user3386372
user3386372

Reputation:

Can not figure out how to find a space, within a string or stringstream in C++

Here is my code, it works for any input. I'm trying to make it so that when you type in a number, it will print out "Hello World!", but if you enter anything other then a single positive number, for example: 1 2, abc, 1 abc, You will get the invalid input prompt. It works for everything except when I input something like "3 2" it just prints out "Hello world!" three times, or whatever number is first, where it's supposed to not print out anything other then the invalid input prompt.

using namespace std;

int main( int argc, char**argv )
{

 cout << "How many times?" << '\n';

 while( !cin.eof() )
 {
  string inputString;
  int    x = 0;
  int    r;

 getline(cin, inputString );
 stringstream s(inputString);

//while loop which, if r > 1, then the input is invalid 
while( s >> x )
{
 r++;
}

   s >> x;

   if( s.fail() || cin.eof() || r > 1 )
     {
        cout << "invalid input, please try again." << '\n';
        s.str("");
        x = 0;
     }

   for(int i = 0; i < x; i++)
     {
        cout << "Hello World!" << endl;
     }
        cout << "How many times?" << '\n';

   if( cin.eof() )
     {
        cout << '\n' << "bye" << endl;
        break; 
     }
}
}

The while( s >> x ) loop tells me that if something like "1 abc def" is entered, then r = 3, but if something like just "1" is entered then r = 1. However I am constantly taking this loop out and adding it back in, because whenever I have it included, the whole thing is ruined. Any input is then deemed invalid. Is there a better way for me to be able to deem a string invalid when there is a space in it?

Upvotes: 0

Views: 3786

Answers (2)

Ethouris
Ethouris

Reputation: 1901

The simplest way to check if you have spaces in the given string is to do

if ( inputString.find(' ') != std::string::npos ) ...

If you want to search for space or tab, then you can:

if ( inputString.find_first_of(" \t") != std::string::npos ) ...

The best "portable" way though would be to check every character whether it is a space-character using the standard std::isspace function:

int (*IsSpace)(int) = std::isspace;
if ( std::find_if(inputString.begin(), inputString.end(), IsSpace)
       != inputString.end() ) ...

(This assignment to IsSpace is necessary because std::isspace is overloaded, so passing std::isspace instead of this IsSpace may result in error in impossible overload resolution).

Upvotes: 1

ninja
ninja

Reputation: 809

You didn't initialize r!

int r=0;

Upvotes: 0

Related Questions