FAQ > Obtain a string from the user (C++)


Match word(s).

If you have any questions or comments,
please visit us on the Forums.

FAQ > How do I... (Level 1) > Obtain a string from the user (C++)

This item was added on: 2003/03/22

There are many ways to get a string from the user in C++, however the two most common use C strings and C++ strings with the getline function.

C string:

#include <iostream>

int main()
{
  char line[256];

  std::cout<<"Enter a string: ";

  if ( std::cin.getline ( line, sizeof line ) )
    std::cout<<"You entered \""<< line <<"\""<<std::endl;
}

C++ std::string:

#include <iostream>
#include <string>

int main()
{
  std::string line;

  std::cout<<"Enter a string: ";

  if ( getline ( std::cin, line ) )
    std::cout<<"You entered \""<< line <<"\""<<std::endl;
}

Credit: Prelude

Additional: MSVC6 information: There is a problem with MSVC6 whereby the getline() function may require the user to press [enter] twice for it to take effect. This is detailed [here], in the section titled Fix to <istream>.

Script provided by SmartCGIs