随笔 - 226,  文章 - 0,  评论 - 4,  阅读 - 30375

相同点:

作为while的条件时,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),如果是循环输入的话(for)会用掉一次循环

复制代码
#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)

posted on   小凉拖  阅读(107)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示