C++ getline函數(shù)用法詳解
雖然可以使用 cin 和 >> 運(yùn)算符來輸入字符串,但它可能會(huì)導(dǎo)致一些需要注意的問題。
當(dāng) cin 讀取數(shù)據(jù)時(shí),它會(huì)傳遞并忽略任何前導(dǎo)白色空格字符(空格、制表符或換行符)。一旦它接觸到第一個(gè)非空格字符即開始閱讀,當(dāng)它讀取到下一個(gè)空白字符時(shí),它將停止讀取。以下面的語句為例:
cin >> namel;
可以輸入 "Mark" 或 "Twain",但不能輸入 "Mark Twain",因?yàn)?cin 不能輸入包含嵌入空格的字符串。下面程序演示了這個(gè)問題:
// 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
請注意,在這個(gè)示例中,用戶根本沒有機(jī)會(huì)輸入 city 城市名。因?yàn)樵诘谝粋€(gè)輸入語句中,當(dāng) cin 讀取到 John 和 Doe 之間的空格時(shí),它就會(huì)停止閱讀,只存儲(chǔ) John 作為 name 的值。在第二個(gè)輸入語句中, cin 使用鍵盤緩沖區(qū)中找到的剩余字符,并存儲(chǔ) Doe 作為 city 的值。
為了解決這個(gè)問題,可以使用一個(gè)叫做 getline 的 C++ 函數(shù)。此函數(shù)可讀取整行,包括前導(dǎo)和嵌入的空格,并將其存儲(chǔ)在字符串對象中。
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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C語言中6組指針和自增運(yùn)算符結(jié)合方式的運(yùn)算順序問題
本文通過代碼實(shí)現(xiàn)分析了6種組合:* p++,(* p)++,* (p++),++* p,++( * p), * (++p),需要的朋友可以參考下2015-07-07
C語言數(shù)據(jù)結(jié)構(gòu)與算法之鏈表(二)
在這篇文章中,我們將拋開令人頭禿的指針和結(jié)構(gòu)體,我們將另外使用一種數(shù)組來實(shí)現(xiàn)的方式,叫做模擬鏈表。讓來跟隨小編一起學(xué)習(xí)學(xué)習(xí)吧2021-12-12
Qt串口通信開發(fā)之Qt串口通信模塊QSerialPort開發(fā)完整實(shí)例(串口助手開發(fā))
這篇文章主要介紹了Qt串口通信開發(fā)之Qt串口通信模塊QSerialPort開發(fā)完整實(shí)例(串口助手開發(fā)),需要的朋友可以參考下2020-03-03
詳解C語言中的錯(cuò)誤報(bào)告errno與其相關(guān)應(yīng)用方法
這篇文章主要介紹了C語言中的錯(cuò)誤報(bào)告errno與其相關(guān)應(yīng)用方法,包括errno和strerror以及perror的介紹,需要的朋友可以參考下2015-08-08
使用c++實(shí)現(xiàn)OpenCV繪制旋轉(zhuǎn)矩形圖形
這篇文章主要給大家介紹了使用c++實(shí)現(xiàn)OpenCV繪制圖形旋轉(zhuǎn)矩形的方法案例,通過圖文及代碼形式進(jìn)行了詳細(xì)的描述,有需要的朋友可以參考下,希望可以有所幫助2021-08-08
C/C++實(shí)現(xiàn)string和int相互轉(zhuǎn)換的常用方法總結(jié)
在C++編程中,經(jīng)常需要在字符串(string)和整型(int)之間進(jìn)行轉(zhuǎn)換,本文將詳細(xì)介紹幾種在C和C++中實(shí)現(xiàn)這兩種類型轉(zhuǎn)換的常用方法,有需要的可以參考下2024-01-01

