混合输入字符串和数字

混合输入字符串和数字
混合输入数字和面向行的字符串会导致问题。如下代码
#include  " stdafx.h "
#include 
< iostream >
using   namespace  std;
int  main( int  argc,  char *  argv[])
{
    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;
}
程序运行情况如下图:
混合输入字符串和数字_第1张图片

      当我输入完1966年,按回车后,根本没有输入地址的机会。问题在于,当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);

你可能感兴趣的:(混合输入字符串和数字)