使用cin和getline()输入字符串

发布时间 2023-04-23 22:53:30作者: 小凉拖

相同点:

作为while的条件时,终止条件均为:Ctrl z(或则Z),执行本循环,执行完后进入下一个循环均为换行符。

1     string s;
2     while (cin >> s)
3     {
4         cout << "you input is:" << endl;
5         cout << s << endl;
6     }
1     string s;
2     while (getline(cin,s))
3     {
4         cout << "you input is:" << endl;
5         cout << s << endl;
6     }

 不同点:

cin:

(1)string对象接收cin输入时,接收的内容区间为:第一个有效字符(空格,换行,制表符不是有效字符)到空格,换行,制表符。

(2)如果换行符输入之前输入内容为John Doe,则string只接收了John,而下次输入时string对象会首先检查输入缓冲区是否有剩余字符,如果有(Doe)则string对象不会输入的内容,而会接收缓冲区内剩余的内容(Doe)

#include <iostream>
#include <string> // Header file needed to use string objects
using namespace std;

int main()
{
    string name;
    string city;
    cout << "Please enter your name: ";
    cin >> name;
    cout << "Enter the city you live in: ";
    cin >> city;
    cout << "Hello, " << name << endl;
    cout << "You live in " << city << endl;
    return 0;
}

程序运行的结果为:

Please enter your name: John Doe
Enter the city you live in: Hello, John
You live in Doe

(3)当cin作为while循环的条件时,

如果输入内容为John Doe,再输入空格时会循环两次,分别输出John和Doe。

1     string s;
2     while (cin >> s)
3     {
4         cout << "you input is:" << endl;
5         cout << s << endl;
6     }

 

 getline():

string对象会接收所有的字符(包括:空格,制表符),直到遇到换行符。

 1 #include <iostream>
 2 #include <string> // Header file needed to use string objects
 3 using namespace std;
 4 
 5 int main()
 6 {
 7     string name;
 8     string city;
 9     cout << "Please enter your name: ";
10     getline(cin, name);
11     cout << "Enter the city you live in: ";
12     getline(cin, city);
13     cout << "Hello, " << name << endl;
14     cout << "You live in " << city << endl;
15     return 0;
16 }

程序运行结果为:

Please enter your name: John Doe
Enter the city you live in: Chicago
Hello, John Doe
You live in Chicago

参考文章:
C++ getline函数用法详解 (biancheng.net)