This question already has an answer here:
I was learning about Maps and string libraries when I thought of compilig the following code.
#include<iostream>
#include<map>
#include<string>
int main()
{
std::map<std::string, double> marks;
std::string name; double mark;
std::cout << "Enter the Name: ";
std::getline(std::cin, name);
std::cout << std::endl << "Enter the marks: ";
std::cin >> mark;
marks[name] = mark;
std::cout << "\n" << name;
std::cout << std::endl << marks.at(name);
name.erase();
std::string name2;
std::cout<<"\nExecutring the second getline:\n";
std::getline(std::cin, name2);
std::cout << name<<std::endl;
std::cout<<name2;
std::cout << "\nhi";
std::cin.get();
}
In the above code the second getline function is not executed and the programs jumps to next line.
when I shifted the lines asking for the marks above the lines asking for name the same thing happens but instead the first getline functions doesn't gets executed. but the second does get executed. I even tried it on repl.it and the same thing happened.
Here is the second code in which two line are shifted above:
#include<iostream>
#include<map>
#include<string>
int main()
{
std::map<std::string, double> marks;
std::string name; double mark;
std::cout << std::endl << "Enter the marks: ";
std::cin >> mark;
std::cout << "Enter the Name: ";
std::getline(std::cin, name);
marks[name] = mark;
std::cout << "\n" << name;
std::cout << std::endl << marks.at(name);
name.erase();
std::string name2;
std::cout<<"\nExecutring the second getline:\n";
std::getline(std::cin, name2);
std::cout << name<<std::endl;
std::cout<<name2;
std::cout << "\nhi";
std::cin.get();
}
Aucun commentaire:
Enregistrer un commentaire