In genuine C++11 or C++14 the correct way to read an entire line is std::getline or std::basic_istream::getline.
Also, you'll better flush the output before reading an input; remember that C++ and C standard IO functions are buffering.
The old C89 gets
function is deprecated since a long time (probably more than ten years), and now forbidden because it is so dangerous (can't avoid a buffer overflow). So please forget it (in C99 or C11, use fgets instead, on POSIX with C99 or C11, use getline; in C++11 or C++14 use as I said std::getline or std::basic_istream::getline).
Your main
's body should be:
string str;
cout << "輸入字串:" << flush;
getline(cin,str);
cout << "輸入的字串:" << str << endl;
return 0;
The advantage of using a std::string
is that your user could input an arbitrarily long line (up to implementation limits, perhaps million of characters).
If you are coding on a POSIX system like MacOSX or Linux, you could use the GNU readline library and function (see also ncurses) when reading on a terminal. The big advantage is that your user is given editing ability (and completion) when typing his line.
PS. General hint when programming: read the documentation of every function that you are using before coding.