Home  >  Article  >  Backend Development  >  How to input string in c++

How to input string in c++

下次还敢
下次还敢Original
2024-05-01 15:39:171125browse

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:

<code class="cpp">getline(cin, string_variable);</code>

Where:

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

Example:

<code class="cpp">#include <iostream>
#include <string>

using namespace std;

int main() {
    string input_string;
    getline(cin, input_string);
    cout << "输入的字符串为:" << input_string << endl;
    return 0;
}</code>

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:

<code class="cpp">cin >> string_variable;</code>

Where:

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

Example:

<code class="cpp">#include <iostream>
#include <string>

using namespace std;

int main() {
    string input_string;
    cin >> input_string;
    cout << "输入的字符串为:" << input_string << endl;
    return 0;
}</code>

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!

Statement:
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