您的位置:首页 > 编程语言 > C语言/C++

C++ cin,_cin.get,cin.getline等函数深入分析+实例详解

2013-03-02 15:46 826 查看
C++读取输入的类和方法有:cin 、cin.getline(str,number)、cin.get(str,number)、getline(cin,str)

1.cin:(面向单词的输入)

      读取输入时,可以跳过保留在输入队列中的空白(Tab/空格/Enter),直到找到非空白为止。

      然后开始读取字符,直到再次遇到空白为止(Tab/空格/Enter)。读取结束后将空白保留在了

      输入队列中。

      简记为:从非空白开始读取,再遇空白截止,将截止时遇到的空白保留在输入队列中。

     例子:cin>>numberEnter  标记为1

                cin>>ageEnter        标记为2

输入队列如下所示:

numberEnter  age Enter  
1读取 1停止    
         

 2跳过2读取2停止  
 

2.cin.getline(str,number):(面向行的输入)

      读取输入时,跳不过保留在输入队列中的空白,遇Enter字符停止读取,将Enter替换为空字符保存

      cin.getline(str,20):读取的字符数只能为19个,最后一个留给空字符

      当输入超过指定的字符数是,本例中若输入>20,则后面的输入将被禁止。

3.cin.get(str,number):(面向行的输入)

      读取输入时,跳不过保留在输入队列中的空白,遇Enter字符停止读取,将Enter保留在输入队列中

      当输入为空时,会设置失效位,禁止后面的输入

4.getline(cin,str)):(面向行的输入)

      string str:当str是string变量时,此语句的作用将cin输入的行,保存到string变量str中;

 

5.当交替读取数值(cin)和字符串(字符串包含多个单词,采用面向行的输入cin.get()/cin.getline())

#include<iostream>

#include<cstring>

#include<string>

using namespace std;

struct car

{

 string  manufacturer;

 int year;

};

int main()

{

 using namespace std;

 cout<<"How many cars do you wish to catalog? ";

 int number;
 cin>>number;//cin将最后的回车符留在输入队列中
 car *vehicle=new car[number];//new与delete应配对使用

 for(int i=0;i<number;i++)

 {

  cout<<"Car #"<<i+1<<":\n";

  cout<<"Please enter the make: ";
  cin.get();//负责读取输入队列中cin留下的回车符

  getline(cin,vehicle[i].manufacturer);//跳不过输入队列中的回车符,若没有用cin.get()读取输入队列中的回车符,

  //getline()将读取(遇回车符被视为结束,)在你没有输入任何数据的情况下,执行cout<<"Please enter the year made: ";语句

  cout<<"Please enter the year made: ";

  cin>>vehicle[i].year;

 }

 cout<<"Here is your collection:\n";

 for(int j=0;j<number;j++)

 {

  cout<<vehicle[j].year<<" "<<vehicle[j].manufacturer<<endl;

 }
 delete []vehicle;

 return 0;

}

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: