To input a string in C, use the getline function, whose parameters include a pointer to the string variable and the input stream object. The steps are as follows: Include the <iostream> header file. Use the cin input stream object. Use getline(cin, stringVariable) to get string input. Note that the getline function gets the entire line of text, including spaces and newlines.
How to enter a string in C
To enter a string in C, you can use getline
Function. This function takes two parameters: a pointer to a string variable and an input stream object.
1. Header file inclusion
First, include the <iostream>
header file in your program, which defines getline
Function:
<code class="cpp">#include <iostream></code>
2. Input stream object
getline
The second parameter of the function is the input stream object. Typically, we will use the cin
input stream object, which represents standard input:
<code class="cpp">std::cin;</code>
3. Get the string input
to be obtained from the user For string input, please use the following syntax:
<code class="cpp">std::getline(cin, stringVariable);</code>
where stringVariable
is the string variable you want to store the input string.
4. Example
The following is an example of getting user input string:
<code class="cpp">#include <iostream> using namespace std; int main() { string name; cout << "Enter your name: "; // 输出提示消息 getline(cin, name); // 获取用户输入的字符串 cout << "Your name is: " << name << endl; // 输出输入的字符串 return 0; }</code>
5. Spaces and newlines
It should be noted that the getline
function will get the entire line of text entered by the user, including spaces and newlines. If you don't want to get these characters, you can use the ignore
function to ignore them. For example, if you only want to get the words entered by the user, you can use the following code:
<code class="cpp">cin.ignore(); getline(cin, word);</code>
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!