11-混合输入字符串和数字
4.2.5 混合输入字符串和数字
混合输入数字和面向行的字符串会导致问题。请看程序清单4.6中的简单程序。
程序清单4.6 numstr.cpp
// numstr.cpp -- following number input with line input
#include <iostream>
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数组。解决之道是,在读取地址之前先读取并丢弃换行符。这可以通过几种方法来完成,其中包括使用没有参数的get()和使用接受一个char参数的get(),如前面的例子所示。可以单独进行调用:
cin >> year;
cin.get(); // or cin.get(ch);
也可以利用表达式cin>>year返回cin对象,将调用拼接起来:
(cin >> year).get(); // or (cin >> year).get(ch);
按上述任何一种方法修改程序清单4.6后,它便可以正常工作:
What year was your house built?
1966
What is its street address?
43821 Unsigned Short Street
Year built: 1966
Address: 43821 Unsigned Short Street
Done!
C++程序常使用指针(而不是数组)来处理字符串。我们将在介绍指针后,再介绍字符串这个方面的特性。下面介绍一种较新的处理字符串的方式:C++ string类。