getline(cin,string)没有给出预期的输出 [英] getline(cin, string) not giving expected output

查看:91
本文介绍了getline(cin,string)没有给出预期的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用c ++ 14。我已经阅读了很多有关该问题的帖子。

Using c++14. I have read many posts regarding the problem.

如果我在下面运行此代码,它将跳过getline行。

If I run this code below, it jumps over the getline lines.

#include <iostream>
#include "main_menu.h"

void MainMenu::AddTest()
{
    std::string courseName = "";
    std::string testName = "";
    std::string date = "";

    std::cout << "Enter course name: " << std::endl;
    std::getline(std::cin, courseName);

    std::cout << "Enter test name: " << std::endl;
    std::getline(std::cin, testName);

    std::cout << "Enter test date: " << std::endl;
    std::getline(std::cin, date);

    Test test(courseName, testName, date);
    tests.Add(test);

    std::cout << "Test registered : " << std::endl;
    tests.Print(test.id);
}

如果我在每条getline行后添加cin忽略(下面示例如何实现) ),则会从输入字符串中删除一些字符,并使用错误的变量来存储它们。请注意,我的字符串带有空格。

If I add cin ignore after each getline lines (example below how I implement it), it deletes some characters from the input strings and uses wrong variables to store them. Note that I have strings with whitespaces.

std::getline(std::cin, courseName); 
std::cin.ignore();

这就是我得到的:

Enter course name: 
History 2
Enter test name:     
History 2 exam
Enter test date: 
2017.01.02
Test registered : 
test id = 2, course name = , test name = istory 2, date = istory 2 exam

我也尝试冲洗cout,但无济于事。

I also tried to flush cout, didn't help.

如果我从主要,我得到了预期的输出,所以问题肯定是cin / getline。

My Print function works like a charm, if I add courses manually from main, I get the expected output, so the problem is definitely the cin / getline.

Test registered : 
test id = 1, course name = History 2, test name = History 2 exam , date = 01.02.2017

我按照以下说明使用getline: http://www.cplusplus .com / reference / string / string / getline /?kw = getline

I use getline as explained here: http://www.cplusplus.com/reference/string/string/getline/?kw=getline

任何帮助将不胜感激,谢谢。

Any help would be much appreciated, thank you.

推荐答案

我正在回答一个古老的问题,但是在使用所有 getline()的。

I'm answering an ancient question, but try clearing the input stream before you use all the getline()'s. It is possible that you have some extra returns in the buffer before you ask for input.

cin.clear();
cin.ignore(INT_MAX);

这篇关于getline(cin,string)没有给出预期的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆