0

I'm new to cpp, it's been 2 weeks since i stared learning.

Today this weird bug or what it is called, causing my code to run weird way and not working as expected, thing is if I use only std::cin code runs perfectly fine but things got shaky when I add std::getline and then the program stops.

Here's my simple code.

#include <iostream>

int main(){

    int age;
    std::cout << "Age: ";
    std::cin >> age;
    std::cout << age << "\n";
    
    std::string Name;
    std::cout << "Name\n";
    std::getline(std::cin, Name);
    std::cout << Name << "\n";

    return 0;
}

output

chitti@Thor /m/4/F/Langs> cd "/mnt/404EA75214A150D1/Files/Langs/Cpp/" && g++ main.cpp -o main && "/mnt/404EA75214A150D1/Files/Langs/Cpp/"main
Age: 55
55
Name

chitti@Thor /m/4/F/L/Cpp>
Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
  • Did you try stepping through the code with a debugger? – Quimby Jan 12 '22 at 09:49
  • If you're using `getline` after `cin >> something,` you need to flush the newline out of the buffer in between. You can do this by using `cin.ignore()` appropriately. – Jason Jan 12 '22 at 09:51
  • @UnholySheep yep! it worked, i searched on internet most of them so confusing and unable to understand....thanks – Charan Reigns Jan 12 '22 at 09:57

0 Answers0