【C++】cin、cin.get(char)和getline()

cin

#include <iostream>
using namespace std;

int main()
{
    char ch;
    int count = 0;
    cout << "Enter character; enter # to quit:\n";
    cin >> ch;
    while (ch != '#')
    {
        cout << ch;
        ++count;
        cin >> ch;
    }
    cout << endl << count << "character read\n";
    return 0;
}

这里写图片描述

为什么会出现上图的结果呢?明明我在字符之间有空格而且难道不应该是我输入一个字符立即输出一个字符么(从代码上看)
原因在于cin。读取数据时,cin将忽略空格和换行符,因此输入中的空格没有被回显,也没有包含在计数内。更为复杂的是,发送给cin的输入被缓冲。这意味着只有在用户按下回车键后,他输入的内容才会被发送给程序。这就是在#后面输入字符的原因。按下回车键后,整个字符序列被发送给程序,但程序遇到#后会结束对输入的处理。(基本上就是cin>>时,你想输入什么就输入什么,程序完全不管你,但是等你按了回车,就将输入的内容传递给程序进行处理)。

cin.get()

#include <iostream>
using namespace std;

int main()
{
    char ch;
    int count = 0;
    cout << "Enter character; enter # to quit:\n";
    cin.get(ch);
    while (ch != '#')
    {
        cout << ch;
        ++count;
        cin.get(ch);
    }
    cout << endl << count << "character read\n";
    return 0;
}

这里写图片描述

如果需要读取每一个字符(包括空格和制表符)可以使用cin.get()。但是输入仍然被缓冲。

getline()

getline()的原型是istream& getline ( istream &is , string &str , char delim );
其中 istream &is 表示一个输入流,譬如cin;string&str表示把从输入流读入的字符串存放在这个字符串中(可以自己随便命名,str什么的都可以);char delim表示遇到这个字符停止读入,在不设置的情况下系统默认该字符为’\n’,也就是回车换行符(遇到回车停止读入)。给大家举个例子:

string line;
cout<<"please cin a line:"
getline(cin,line,'#');
cout<<endl<<"The line you give is:"line;

那么当我输入”You are the #best!” 的时候,输入流实际上只读入了”You are the “,#后面的并没有存放到line中(应该是在缓冲区里吧)。然后程序运行结果应该是这样的:
please cin a line:You are the #best!
The line you give is:You are the
而且这里把终止符设为#,你输入的时候就算输入几个回车换行也没关系,输入流照样会读入,譬如:
please cin a line:You are the best!
//这里输入了一个回车换行
Thank you!
# //终止读入
The line you give is:You are the best!
//换行照样读入并且输出
Thank you!
以上就是getline()函数一个小小的实例了。

猜你喜欢

转载自blog.csdn.net/siyue0211/article/details/76976661
今日推荐