Link to home
Start Free TrialLog in
Avatar of bfunieru1
bfunieru1

asked on

How to use a default value for a string input from console in ANSI c++

Does anybody knows a standard function in ANSI C++ which accepts a default value of the input value for reading a string from console?

For example I need that the user inputs something like a name but already gets into the console an default name ("John Doe") which he can change. Is there such a function or code block available?




Avatar of evilrix
evilrix
Flag of United Kingdom of Great Britain and Northern Ireland image

Are you referring to passing the "name" as a command line parameter or maybe reading from stdin when starting the process? You question is a little unclear.

FWIW, there are no "standard" ANSI C++ functions that will do what you ask but once your requirement is understood it shouldn't be too hard to cobble a solution together for you.
Avatar of bfunieru1
bfunieru1

ASKER

The later. Not a command line parameter after program name.

It should be something as what one get from a function as cin or gets.

Hi,

if I understand correctly you want the user to input a name, but if i.e. the user just hits ENTER a default name should be used, right?

If so see the attached code ...

Hope that helps,

ZOPPO
std::string getName( const std::string strDefault )
{
	std::string strName;
	std::cout << "Enter your name [default='" << strDefault << "']: ";
	getline( std::cin, strName );

	if ( false != strName.empty() )
	{
		strName = strDefault;
	}

	return strName;
}

int main(int argc, char* argv[])
{
	std::string strName = getName( "John Doe" );

	std::cout << "Entered name: '" << strName << "'" << std::endl;

	return 0;
\

Open in new window

This solution can also work for sure.
I will prefer if it will be possible to  change something in the default string if for example instead of the short "John Doe" is something much longer which will make new writing very anoying.

To make it more clear it should act similar to a windows textbox which has a default text which one can change or if it is OK just press ENTER and send it.
ASKER CERTIFIED SOLUTION
Avatar of Zoppo
Zoppo
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial