cin.get(), cin.getline() 用法

cin.getline( name, LEN )可以读取一行字符串,通过换行符确定已经读到行尾,但它不保存换行符。

cin.get( name, LEN )可以读取一行字符串,但会将换行符留在输入队列当中,后面程序出现cin读取输入时,cin会先读到换行符从而忽略过去。

所以,可以写成这样:

cin.get(name, LEN);  // Read first line.

cin.get(); // Read new line.

cin.get(name2, LEN);  //Read second line.

cin.get()返回一个cin对象,所以可以这么去用,下面两种语句相同:

cin.get(name, LEN).get();  

cin.getline(name1, LEN).getline(name2, LEN);

 

numstr.cpp

  cout << "What year was your house built? \n";

  int year ;

  cin >> year;

  cout << "What is its street address?\n";

  char address[80];

  cin.getline(adress, 80);

  cout << "year built: " << year << endl; 

  cout << "Address :" << address << endl;

  cout<< "Done!"<< "\n";

  return 0; 

用户输入year后,会将换行留在输入队列,导致输入address的时候,cin先读到换行,直接导致输入结束。

解决方案可以用 cin.get 加入到 cin >> year;之后。

或者 (cin >> year) . get();

 

posted @ 2017-09-18 01:49  Bear_Guo  阅读(310)  评论(0编辑  收藏  举报