How to input string in c++

下次还敢
Release: 2024-05-01 15:39:17
Original
1010 people have browsed it

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.

How to input string in c++

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);
Copy after login

Where:

  • cin: standard input stream object
  • string_variable: string variable that stores the input string

Example:

#include  #include  using namespace std; int main() { string input_string; getline(cin, input_string); cout << "输入的字符串为:" << input_string << endl; return 0; }
Copy after login

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;
Copy after login

Where:

  • cin: standard input stream object
  • string_variable: string variable that stores the input string

Example:

#include  #include  using namespace std; int main() { string input_string; cin >> input_string; cout << "输入的字符串为:" << input_string << endl; return 0; }
Copy after login

Run the above code to prompt the user to enter a word or space-delimited string, and then output the entered string.

Note:

  • If the input string contains spaces, you need to use quotation marks to enclose the string when using the cin >> operator.
  • If you need to read multi-line strings, you can use the getline function with a while loop.
  • 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!

Related labels:
c++
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!