首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C++ 字符串輸入輸出:getline 與 cin.getline 正確用法對比

     編輯:程式設計疑難解答

問題現象

用戶嘗試用 char[] 和 string 分別實現相同功能,但 string 版本編譯報錯或運行異常。

錯誤代碼分析

// 錯誤嘗試:對 string 使用 cin.getline
string name;
name.resize(20); // 僅設置大小,不改變內部緩衝區指針
cin.getline((char*)name.c_str(), 20); // 錯誤!c_str() 返回 const char*,不可修改
// 強制轉型 (char*) 導致未定義行為,可能崩潰

正確的等效實現

方案一:純 string 版(推薦)

#include <iostream>
#include <string>
using namespace std;

int main() {
    string name, dessert;
    cout << "Enter your name:\n";
    getline(cin, name); // 標準 C++ 讀取整行
    cout << "Enter your favorite dessert:\n";
    getline(cin, dessert);
    cout << "I have some delicious " << dessert 
         << " for you, " << name << ".\n";
    return 0;
}

方案二:純 char 數組版

#include <iostream>
using namespace std;

int main() {
    const int SIZE = 20;
    char name[SIZE], dessert[SIZE];
    cout << "Enter your name:\n";
    cin.getline(name, SIZE);
    cout << "Enter your favorite dessert:\n";
    cin.getline(dessert, SIZE);
    cout << "I have some delicious " << dessert 
         << " for you, " << name << ".\n";
    return 0;
}

方案三:混合使用(教學演示)

#include <iostream>
#include <string>
#include <cstring> // strcpy
using namespace std;

int main() {
    const int SIZE = 20;
    char name[SIZE], dessert[SIZE];
    string sName, sDessert;

    // char[] 輸入
    cout << "Enter name (char[]):\n";
    cin.getline(name, SIZE);
    sName = name; // 隱式轉換 char* -> string

    // string 輸入
    cout << "Enter dessert (string):\n";
    getline(cin, sDessert);
    strncpy(dessert, sDessert.c_str(), SIZE-1); // 反向複製
    dessert[SIZE-1] = '\0';

    // 輸出驗證
    cout << "char[] name: " << name << endl;
    cout << "string name: " << sName << endl;
    cout << "char[] dessert: " << dessert << endl;
    cout << "string dessert: " << sDessert << endl;
    return 0;
}

核心知識點

操作string 正確方法char[] 正確方法
讀取整行getline(cin, str)cin.getline(arr, size)
字符串複製s1 = s2strcpy(des, src) / strncpy
轉換關係string s = char_arr / s.c_str() (const char*)strcpy(arr, s.c_str())
長度獲取s.length() / s.size()strlen(arr)

為什麼 (char*)name.c_str() 是錯誤的?

  • c_str() 返回 const char*,指向 string 內部只讀緩衝區。
  • 強制去除 const 並寫入,違反 C++ 類型安全,可能導致程序崩潰、數據損壞或安全漏洞。
  • resize() 僅改變邏輯長度,不保證底層緩衝區可寫或足夠大。

總結

不要嘗試對 std::string 使用 C 風格輸入函數。兩套體系各有專用 API,混用需通過正確轉換(賦值、c_str()、strcpy)完成。教學中建議分開演示,避免混淆。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved