node ninja
node ninja

Reputation: 33026

Getting string input with a default value supplied in C++

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++?

Upvotes: 1

Views: 991

Answers (3)

Maciej Ziarko
Maciej Ziarko

Reputation: 12104

#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;
}

Upvotes: 4

Hari
Hari

Reputation: 5227

Just use two strings: Default string and User_supplied string. Get the input from the user (for the user_supplied string) and do an strlen on this string to check if it has a length greater than zero. If so use the User_supplied string, else use the default string

Upvotes: 1

flight
flight

Reputation: 7272

You should be able to do it with the version of getline() defined in . You can use it like this:

#include <iostream>
#include <string>
using namespace std;

int main()
{
  string str;
  getline(cin,str);
  // Use str
}

Upvotes: 1

Related Questions