No.1 cin.getline()
// instr2.cpp -- reading more than one word with getline
#include
int main()
{
using namespace std;
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];
cout << "Enter your name:\n";
cin.getline(name, ArSize); // reads through newline
cout << "Enter your favorite dessert:\n";
cin.getline(dessert, ArSize);
cout << "I have some delicious " << dessert;
cout << " for you, " << name << ".\n";
return 0;
}
输出代码
Enter your name:
Dirk Hammernose
Enter your favorite dessert:
Radish Torte
I have some delicious Radish Torte for you, Dirk Hammernose.
getline函数读取整行,通过回车键输出的换行符来确定行尾。cin.getline()读取指定字符或换行符停止。 cin.getline(name,20) name是数组,20是元素个数
No.2 cin.get() 这是一种错误编译
// numstr.cpp -- following number input with line input
#include
int main()
{
using namespace std;
cout << "What year was your house built?\n";
int year;
cin >> year;
cout << "What is its street address?\n";
char address[80];
cin.getline(address, 80);
cout << "Year built: " << year << endl;
cout << "Address: " << address << endl;
cout << "Done!\n";
return 0;
}
What year was your house built?
1966
What is its street address?
Year built: 1966
Address:
Done!
cin读取年份,回车键生成换行符留在输出队列中,cin.getline()认为是一个空行,就将一个空字符串赋值给address数组,我们要解决就是丢弃这个换行符。 我们可以单独调用
cin>>year;
cin.get();
也可以用
(cin>>year).get()
cin.get()其他用法
// instr3.cpp -- reading more than one word with get() & get()
#include
int main()
{
using namespace std;
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];
cout << "Enter your name:\n";
cin.get(name, ArSize).get(); // read string, newline
cout << "Enter your favorite dessert:\n";
cin.get(dessert, ArSize).get();
cout << "I have some delicious " << dessert;
cout << " for you, " << name << ".\n";
return 0;
}
输出
Enter your name:
Mai Parfait
Enter your favorite dessert:
Chocolate Mousse
I have some delicious Chocolate Mousse for you, Mai Parfait.
输出连在一起,这些应用需要实记。 补充: