C++ getline函數用法詳解


轉載自http://c.biancheng.net/view/1345.html

 

雖然可以使用 cin 和 >> 運算符來輸入字符串,但它可能會導致一些需要注意的問題。

當 cin 讀取數據時,它會傳遞並忽略任何前導白色空格字符(空格、制表符或換行符)。一旦它接觸到第一個非空格字符即開始閱讀,當它讀取到下一個空白字符時,它將停止讀取。以下面的語句為例:

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 使用鍵盤緩沖區中找到的剩余字符,並存儲 Doe 作為 city 的值。

為了解決這個問題,可以使用一個叫做 getline 的 C++ 函數。此函數可讀取整行,包括前導和嵌入的空格,並將其存儲在字符串對象中。

getline 函數如下所示:

getline(cin, inputLine);

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

// 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM