gpt4 book ai didi

c++ - cin.getline 正在跳过一行输入并获取下一行

转载 作者:搜寻专家 更新时间:2023-10-31 01:21:20 26 4
gpt4 key购买 nike

为什么 cin.getline 开始处理正文输入的第二行,但在第一行中断?

示例程序运行:

Enter name: Will
Enter body: hello world
hello again <= It accepts this one



char* name = new char[100];
char* body = new char[500];

std::cout << "Enter name: ";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin.getline(name, 100);

std::cout << "Enter body: ";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin.getline(body, 500');
std::cin >> body;

最佳答案

正如 JoshD 所说,但另外,使用 std::string 可以省去很多工作和痛苦。和 std::getline来自 <string>标题。

喜欢...

#include <string>
#include <iostream>
int main()
{
using namespace std;
std::string name;
cout << "Enter name: "; getline( cin, name );
}

干杯,

– 阿尔夫

关于c++ - cin.getline 正在跳过一行输入并获取下一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3898376/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com