Home > Backend Development > C++ > body text

How to enter a string in c++

下次还敢
Release: 2024-05-06 17:12:13
Original
880 people have browsed it

C Methods for inputting strings: 1) Direct input: cin >> str; 2) Specified size input: cin.get(str, size); 3) Whole line input: getline(cin, str).

How to enter a string in c++

How to enter a string in C

Directly enter

  • cin >> str; Read a single word from standard input and store it in the variable str. Note that it stops reading when it encounters a space or newline character.
  • cin.get(str, size); Read a string of the specified size (including the null character) from the standard input and store it in the array str.

getline

  • getline(cin, str); Read the entire line from standard input, including spaces and newlines character, stored in the string str.

The following example demonstrates these methods:

<code class="c++">int main() {
    string str1, str2;

    // 直接输入单词
    cout << "请输入一个单词:" << endl;
    cin >> str1;

    // 使用 getline 输入整行
    cout << "请输入一行文字:" << endl;
    getline(cin, str2);

    // 输出输入的字符串
    cout << "输入的单词:" << str1 << endl;
    cout << "输入的行:" << str2 << endl;

    return 0;
}</code>
Copy after login

Notes:

  • getline will not ignore the spaces at the end of the line, so you need to use the trim() method to remove excess spaces.
  • getline(cin, str, '\n'); can be used to read the file content line by line.

The above is the detailed content of How to enter a 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 Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template