cin.get()使用注意事项
cin.get()在使用时候不会读取字符串最后的\0,导致\0在下一次输入时会i继续在cin输入流中,导致程序无法输入。
#include<iostream>
using namespace std;
struct inflatable
{
char name[20];
int volume;
int price;
char color[10];
};
int main()
{
inflatable *ps = new inflatable;
cout << "enter a name:";
cin.get(ps->name,20);
// cin.get(ps->name,20).get();
cout << ps->name << endl;
cout << "enter a color:";
cin.get(ps->color,10).get();
cout << (*ps).color << endl;
cin >> ps->volume;
cout << ps->volume << endl;
cin >> (*ps).price;
cout << (*ps).price << endl;
delete ps;
return 0;
}
//输出:
enter a name:ad
ad
enter a color:
0
0
解决办法就是用cin.get().get 或者 cin.get() 帮助读取字符串后的\0即可:
#include<iostream>
using namespace std;
struct inflatable
{
char name[20];
int volume;
int price;
char color[10];
};
int main()
{
inflatable *ps = new inflatable;
cout << "enter a name:";
// cin.get(ps->name,20);
cin.get(ps->name,20).get();
cout << ps->name << endl;
cout << "enter a color:";
cin.get(ps->color,10);
cin.get();
cout << (*ps).color << endl;
cin >> ps->volume;
cout << ps->volume << endl;
cin >> (*ps).price;
cout << (*ps).price << endl;
delete ps;
return 0;
}
//输出
enter a name:d
d
enter a color:d
d
1
1
1
1