Skip to content

Instantly share code, notes, and snippets.

@tjkhara
Created September 28, 2018 09:57
Show Gist options
  • Select an option

  • Save tjkhara/58cae7588a82fa97b3447040315ca9c7 to your computer and use it in GitHub Desktop.

Select an option

Save tjkhara/58cae7588a82fa97b3447040315ca9c7 to your computer and use it in GitHub Desktop.
Validating against newline returns
#include <iostream>
#include <iomanip>
#include <string>
using std::cout;
using std::cin;
using std::endl;
using std::string;
void checkEmpty(string inputString)
{
bool continueAsking = false;
bool isEmpty= false;
// Check first time
if(inputString == "" || inputString == "\n")
{
continueAsking = true;
}
else
{
continueAsking = false;
}
while(continueAsking)
{
cout << "ERROR! Cannot be an empty string or line return. Enter a positive number: " << endl;
getline(cin, inputString);
if(inputString == "" || inputString == "\n")
{
continueAsking = true;
}
else
{
continueAsking = false;
break;
}
}
}
int main() {
string inputString;
cout << "Enter a value: " << endl;
getline(cin, inputString);
checkEmpty(inputString);
cout << "Value of inputString is " << inputString << endl;
string inputString2;
cout << "Enter a value: " << endl;
getline(cin, inputString2);
checkEmpty(inputString2);
cout << "Value of inputString2 is " << inputString2 << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment