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

标签 c++ cin getline

为什么 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> header 。

喜欢...

#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/

相关文章:

c# - 如何获取每个进程的带宽?

c++ - 为什么 std::cin 同时接受多个输入?

c++ - 遍历文件的每一行

c++ - C 错误 "s1, s2 are used uninitialised in this function"

c++ - 如何访问 vector 值 std::vector <cv::Point2f> pto

c++ - 如何找到此 MSDN 文档中引用的实际值?

C++ 最小/最大函数错误 (C2665)

检查 stdin 中读取的行格式为 number^number

c++ - 无法解决问题

c++ - 控制台未返回 cin 缓冲区中预期的字符数