1

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

1
  • 2
    In a console application or a GUI? If a GUI, which framework? Commented Mar 16, 2011 at 8:48

3 Answers 3

4
#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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

The correct way for checking if a string is empty is to call .empty() instead of .size().
Yes, I must agree. I changed it to !tmp.empty()
= shouldn't be used for setting strings, but it's ok here because it's a const right?
1

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
}

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.