C++ getline函數(shù)用法詳解
雖然可以使用 cin 和 >> 運算符來輸入字符串,但它可能會導致一些需要注意的問題。
當 cin 讀取數(shù)據(jù)時,它會傳遞并忽略任何前導白色空格字符(空格、制表符或換行符)。一旦它接觸到第一個非空格字符即開始閱讀,當它讀取到下一個空白字符時,它將停止讀取。以下面的語句為例:
cin >> namel;
可以輸入 "Mark" 或 "Twain",但不能輸入 "Mark Twain",因為 cin 不能輸入包含嵌入空格的字符串。下面程序演示了這個問題:
// 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;
}
程序輸出結果:
Please enter your name: John Doe
Enter the city you live in: Hello, John
You live in Doe
請注意,在這個示例中,用戶根本沒有機會輸入 city 城市名。因為在第一個輸入語句中,當 cin 讀取到 John 和 Doe 之間的空格時,它就會停止閱讀,只存儲 John 作為 name 的值。在第二個輸入語句中, cin 使用鍵盤緩沖區(qū)中找到的剩余字符,并存儲 Doe 作為 city 的值。
為了解決這個問題,可以使用一個叫做 getline 的 C++ 函數(shù)。此函數(shù)可讀取整行,包括前導和嵌入的空格,并將其存儲在字符串對象中。
getline 函數(shù)如下所示:
getline(cin, inputLine);
其中 cin 是正在讀取的輸入流,而 inputLine 是接收輸入字符串的 string 變量的名稱。下面的程序演示了 getline 函數(shù)的應用:
// 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;
}
程序輸出結果:
Please enter your name: John Doe
Enter the city you live in: Chicago
Hello, John Doe
You live in Chicago
到此這篇關于C++ getline函數(shù)用法詳解的文章就介紹到這了,更多相關C++ getline函數(shù)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Qt串口通信開發(fā)之Qt串口通信模塊QSerialPort開發(fā)完整實例(串口助手開發(fā))
這篇文章主要介紹了Qt串口通信開發(fā)之Qt串口通信模塊QSerialPort開發(fā)完整實例(串口助手開發(fā)),需要的朋友可以參考下2020-03-03
C/C++實現(xiàn)string和int相互轉換的常用方法總結
在C++編程中,經(jīng)常需要在字符串(string)和整型(int)之間進行轉換,本文將詳細介紹幾種在C和C++中實現(xiàn)這兩種類型轉換的常用方法,有需要的可以參考下2024-01-01

