I want to get string input from the user. At the same time, I want to supply a default string so that if the user doesn't want to change it, they can just press enter. How can that be done in C++?
3 Answers
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* args[])
{
const string defaultText = "Default string";
string str;
string tmp;
getline(cin, tmp);
if (!tmp.empty()) //user typed something different than Enter
str = tmp;
else //otherwise use default value
str = defaultText;
cout << str << endl;
}
3 Comments
CadentOrange
The correct way for checking if a string is empty is to call .empty() instead of .size().
Maciej Ziarko
Yes, I must agree. I changed it to
!tmp.empty()node ninja
= shouldn't be used for setting strings, but it's ok here because it's a const right?