getline(cin, string) not giving expected output

 ̄綄美尐妖づ 提交于 2019-12-24 19:17:02

问题


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

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);
}

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();

This is what I get:

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

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

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

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

Any help would be much appreciated, thank you.


回答1:


By using cin.ignore you are messing with the input itself. If you want to get rid of \n character you don't have to! getline will just do that automatically. So just don't use ignore function and the code will be fine. This works:

#include<iostream>

using namespace std;

int main()
{
   string courseName = "";
   string testName = "";
   string date = "";

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

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

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

   cout << courseName << endl;
   cout << testName << endl;
   cout << date << endl;
   return 0;
}



回答2:


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);


来源:https://stackoverflow.com/questions/46204672/getlinecin-string-not-giving-expected-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!