There are two methods for string input in C: getline function, which reads the entire line of string, including spaces. cin >> operator, reads a single word or a space-delimited string.
String input in C
There are two ways to input strings through cin in C:
1. getline function
The getline function is used to read an entire line of strings from the standard input stream, including spaces. The syntax is as follows:
getline(cin, string_variable);
Where:
Example:
#include #include using namespace std; int main() { string input_string; getline(cin, input_string); cout << "输入的字符串为:" << input_string << endl; return 0; }
Run the above code, prompt the user to enter a string, and then output the entered string.
2. cin >> operator
cin >> operator is used to read a single word or space-delimited characters from the standard input stream string. It ignores leading spaces until the first non-space character is encountered. The syntax is as follows:
cin >> string_variable;
Where:
Example:
#include #include using namespace std; int main() { string input_string; cin >> input_string; cout << "输入的字符串为:" << input_string << endl; return 0; }
Run the above code to prompt the user to enter a word or space-delimited string, and then output the entered string.
Note:
The above is the detailed content of How to input string in c++. For more information, please follow other related articles on the PHP Chinese website!