cin,get,getline

一、cin

1.cin使用空白(空格、制表符和换行符)来确定字符串结束的位置,并且对于换行符,cin会把换行符留在输入队列。cin读取字符串放到数组中,并自动在结尾添加空字符。

例如:

char name[20];
cin>>name;

输入:David Smith
cin只会把David放到name数组中并添加空字符'\0'
    cout << "What year was your house built?\n";
    int year;
    cin >> year;
    // cin.get();
    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";
    // cin.get();
    return 0; 
输入:
1996
 如果没有cin.get(),cin>>year会把换行符留在输入队列,则cin.getline会把读取换行符并丢弃掉,address字符串为空

2.发送给cin的输入被缓冲,只有用户按下回车键后,输入的内容才会发送给程序。

    char ch;
    int count = 0;      // use basic input
    cout << "Enter characters; enter # to quit:\n";
    cin >> ch;          // get a character
    while (ch != '#')   // test the character
    {
        cout << ch;     // echo the character
        ++count;        // count the character
        cin >> ch;      // get the next character
    }
    cout << endl << count << " characters read\n";
输入:
see ken run#really fast
输出:
seekenrun

cin忽略空格和换行符,所以输入的空格没有回显;发送给cin的输入被缓冲,所以输入#后,后面还可以输入其他字符;

 

二、cin.getline()

getline 读取一行字符串,直到到达换行符,随后getline将丢弃换行符。

 

三、cin.get()

1.cin.get(str,num)

读取一行字符串,直到到达换行符,将换行符保留到输入序列中。

2.cin.get(char) 读取一个字符

cin.get(ch)读取输入中的下一个字符(包括空格和换行符),但输入仍被缓冲。

3.cin.get() 读取缓冲区的一个字符,返回值为char。

posted @ 2018-03-06 11:23  蓝天飞翔的白云  阅读(1266)  评论(0编辑  收藏  举报