C++——getline()注意事项
在做练习题时遇到了以下问题
#include<iostream>
#include<string>
using namespace std;
struct Information
{
string name;
double diameter;
double weight;
};
int main()
{
Information *a=new Information;
cout << "What is the diameter?";
cin >> (*a).diameter;
cout << "What is the name? ";
getline(cin, a->name);
cout << "What is the weight?";
cin >> (*a).weight;
cout << "example:\n";
cout << "name:" << a->name <<endl;
cout << "weight:" << (*a).weight <<endl;
cout << "diameter:" << (*a).diameter<<endl;
return 0;
}
出来的结果是可以看到直接跳过了getline()
搜查资料后发现是因为自动读取了上一次输入的换行符(和cin.get())很像,于是我们可以提前把换行符“吸收”
cout << "What is the name? ";
getline(cin, a->name);
getline(cin, a->name);
出来的结果就正常了