使用 char 数据类型时遇到 cin.getline() 问题

问题描述 投票:0回答:1

为什么如果我在 arr2 中输入“12345”,程序会跳过 cin.getline(arr3,6,'#') 并完成?

#include <iostream>
#include <string>

using namespace std;

int main() {
    string text;
    char arr2[10];
    char arr3[6];
    cout << "enter value" <<endl;
    getline(cin,text);
    cin.getline(arr2,5,'#');
    cin.getline(arr3,6,'#');
    cout << "results : " << endl;
    cout << " arr1 is : " << arr1 << endl;
    cout <<" arr2 is : " << arr2 << endl;
    cout <<" arr3 is : " << arr3 ;
    return 0 ;
}

执行示例:

enter value
mo
12345
results :
 arr1 is : mo
 arr2 is : 1234
 arr3 is :
Process finished with exit code 0`

c++ c++17 getline
1个回答
0
投票

cin.getline() 中的最后一个参数表示输入结束,即分隔符。将这些行替换为您要修复的代码。

cin.getline(arr1,10,'\n');
cin.getline(arr2,10,'\n');
cin.getline(arr3,6,'\n');

语法是

cin.getline(your_array, max_characters, delimiter);

\n
表示换行(对于此代码,它代表按下 ENTER)

© www.soinside.com 2019 - 2024. All rights reserved.