1.getline()的使用:
char name[20];
cin >> name;
如果用这种方式输入,当碰到输入诸如Dirk Hamernose这样分开的名字时,就会出现问题。只有使用
char name[20];
cin.getline(name,20);
这种方法可以解决输入复杂名字的情况。
getline()函数每次读取一行,它通过换行符来确定行尾,但不保存换行符。
string list[5];
for(int i = 0; i < 5; i++)
getline(cin, list[i]);
2.get()的使用:
char name[20],dessert[20];
cin.get(name,20);
cin.get(dessert,20);
这种情况,在输入name的时候会是正常的,但是由于get()函数保存换行符,所以下次再使用get()函数时,碰到的是换行符,会认为已到达行尾,而没有发现任何可读取的内容,所以会出问题,正确的解决方法如下:
char name[20], dessert[20];
cin.get(name,20);
cin.get();
cin.get(dessert,20);
通过加入cin.get();这句,cin.get();可以读取下一个字符,把换行符读取了,就可以解决该问题。还有一种方法就是上述方法的简写:
char name[20],dessert[20];
cin.get(name,20).get();
cin.get(dessert,20);
get()函数的妙用:
int year;
char address[80];
cout << "input the year: ";
cin >> year;
cout << "input the address: ";
cin.getline(address,80);
cout << "year is " << year << " and address is " << address << endl;
这种情况下,就会出问题,在输入year之后,然后调用getline()看到换行符后,讲认为读取的是一个空行,就把空字符串赋给address,就显示不正常了,正确解决方法如下:
int year;
char address[80];
cout << "input the year: ";
cin >> year;
cin.get();
cout << "input the address: ";
cin.getline(address,80);
cout << "year is " << year << " and address is " << address << endl;
或者
int year;
char address[80];
cout << "input the year: ";
(cin >> year).get();
cout << "input the address: ";
cin.getline(address,80);
cout << "year is " << year << " and address is " << address << endl;