最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C++ getline函數(shù)用法詳解

 更新時(shí)間:2021年02月02日 11:32:00   投稿:zx  
這篇文章主要介紹了C++ getline函數(shù)用法詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

雖然可以使用 cin 和 >> 運(yùn)算符來(lái)輸入字符串,但它可能會(huì)導(dǎo)致一些需要注意的問(wèn)題。

當(dāng) cin 讀取數(shù)據(jù)時(shí),它會(huì)傳遞并忽略任何前導(dǎo)白色空格字符(空格、制表符或換行符)。一旦它接觸到第一個(gè)非空格字符即開(kāi)始閱讀,當(dāng)它讀取到下一個(gè)空白字符時(shí),它將停止讀取。以下面的語(yǔ)句為例:

cin >> namel;

可以輸入 "Mark" 或 "Twain",但不能輸入 "Mark Twain",因?yàn)?cin 不能輸入包含嵌入空格的字符串。下面程序演示了這個(gè)問(wèn)題:

// This program illustrates a problem that can occur if
// cin is used to read character data into a string object.
#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;
}

程序輸出結(jié)果:
Please enter your name: John Doe
Enter the city you live in: Hello, John
You live in Doe

請(qǐng)注意,在這個(gè)示例中,用戶根本沒(méi)有機(jī)會(huì)輸入 city 城市名。因?yàn)樵诘谝粋€(gè)輸入語(yǔ)句中,當(dāng) cin 讀取到 John 和 Doe 之間的空格時(shí),它就會(huì)停止閱讀,只存儲(chǔ) John 作為 name 的值。在第二個(gè)輸入語(yǔ)句中, cin 使用鍵盤緩沖區(qū)中找到的剩余字符,并存儲(chǔ) Doe 作為 city 的值。

為了解決這個(gè)問(wèn)題,可以使用一個(gè)叫做 getline 的 C++ 函數(shù)。此函數(shù)可讀取整行,包括前導(dǎo)和嵌入的空格,并將其存儲(chǔ)在字符串對(duì)象中。

getline 函數(shù)如下所示:

getline(cin, inputLine);

其中 cin 是正在讀取的輸入流,而 inputLine 是接收輸入字符串的 string 變量的名稱。下面的程序演示了 getline 函數(shù)的應(yīng)用:

// This program illustrates using the getline function
//to read character data into a string object.
#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: ";
 getline(cin, name);
 cout << "Enter the city you live in: ";
 getline(cin, city);
 cout << "Hello, " << name << endl;
 cout << "You live in " << city << endl;
 return 0;
}

程序輸出結(jié)果:
Please enter your name: John Doe
Enter the city you live in: Chicago
Hello, John Doe
You live in Chicago

到此這篇關(guān)于C++ getline函數(shù)用法詳解的文章就介紹到這了,更多相關(guān)C++ getline函數(shù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

建昌县| 益阳市| 台前县| 炎陵县| 蓝山县| 黔江区| 沁源县| 浮梁县| 张家港市| 德令哈市| 新余市| 申扎县| 玛多县| 榆树市| 新竹县| 澎湖县| 镇康县| 通榆县| 平原县| 峨眉山市| 萝北县| 南木林县| 古交市| 淮安市| 怀来县| 柞水县| 西藏| 北宁市| 彰化市| 镇远县| 洪雅县| 玉门市| 天全县| 观塘区| 金川县| 东海县| 铅山县| 梁山县| 卓尼县| 阳信县| 江津市|