0

I have issue with my piece of code. I tried find answer already but nothing that applies to my code realy worked. So here is the thing, Im trying get multiple characters input using string and save it in variable inside either switch or if statement doest realy matter I can adapt code to any of othese. Problem is I can easly save one word to my variable using cin but somehow cannot manage to get multiple words saved in my 2nd variable. I think its little mistake or something made wrong at my side but I realy have no idea where Im making mistake.

the main concept of software is using class with priv field of map and few basic funtions inside to manipulate field inside while keeping main.cpp clean and separate it on modules functions. below is first module funtion responsible for adding word with definition to map.Im using namespace std in main.cpp so not need to use std:: all time.

string userInputKey, userInputDef;
cout << "section 1.) add word to dictionary" << endl;
cin >> userInputKey;
cout <<"Ur word input: "<< userInputKey << endl;
cout << "What definition U want to provide for that word: " << endl;
getline(cin, userInputDef);
cin.get();
cout << "Ur def input is: " << endl;

Dictionary newWord;
newWord.setWord(userInputKey,userInputDef);
mainMenu();

after calling function it should execute code above somehow variable userInputDef doesn't want to be working as intended. Im using Visual studio community edition 2019.while program running section 1

Rafal
  • 1
  • You aren't actually printing the userInputDef variable here: `cout << "Ur def input is: " << endl;` – Viktoriya Malyasova Jan 24 '21 at 08:49
  • It's simple `cin >> userInputKey;` reads a word but does not read the newline after that word. Then `getline(cin, userInputDef);` reads the unread newline that you typed after the word. It doesn't wait for any more input, there's an unread newline so it just reads that. See duplicate for what you should do about this. – john Jan 24 '21 at 08:50
  • Thanks a lot all for help. The code that helped me was (cin >> userInputKey).get(); Realy apreciate that tried many things yesterday and coundnt managed to solve it until now :) – Rafal Jan 24 '21 at 09:24
  • @Rafal That code only works if there is a single unread character after the word (because `get` only reads a single character). Try typing 'word space newline'. The correct solution is to use `ignore` as described in the duplicate, – john Jan 24 '21 at 09:28
  • Thanks for advice I will do that in future projects if will need. However in this particular one I just wanted to consume single line as key variable is just single word. – Rafal Jan 24 '21 at 14:03

0 Answers0