getline(cin, string) not giving expected output -


using c++14. have read many posts regarding problem.

if run code below, jumps on 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 add cin ignore after each getline lines (example below how implement it), deletes characters input strings , uses wrong variables store them. note have strings whitespaces.

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

this 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 tried flush cout, didn't help.

my print function works charm, if add courses manually main, expected output, problem cin / getline.

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

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

any appreciated, thank you.

by using cin.ignore messing input itself. if want rid of \n character don't have to! getline automatically. don't use ignore function , code fine. 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; } 

Comments

Popular posts from this blog

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -

python - Error while using APScheduler: 'NoneType' object has no attribute 'now' -