cin >> str1[20]; // 錯誤:str1[20] 是第 21 個字元 (越界),且只讀單一字元
cin >> str2[20];
...
正確寫法:cin >> str1; (陣列名退化為指標,operator>> 會讀取整行字串至空白字元)。
#include <iostream>
#include <cstring> // strcmp, strcpy
#include <algorithm> // std::swap (C++11)
using namespace std;
void swapStr(char *p1, char *p2) {
// 使用暫存陣列交換內容
char temp[20];
strcpy(temp, p1);
strcpy(p1, p2);
strcpy(p2, temp);
// 或 C++11: std::swap_ranges(p1, p1+20, p2); // 需確保長度一致
}
int main() {
char str1[20], str2[20], str3[20], str4[20];
cout << "請輸入四個字串 (空白分隔):";
cin >> str1 >> str2 >> str3 >> str4; // 連續讀取,遇空白斷開
// 簡單選擇排序 (四元素可直接硬編碼比較)
if (strcmp(str1, str2) > 0) swapStr(str1, str2);
if (strcmp(str1, str3) > 0) swapStr(str1, str3);
if (strcmp(str1, str4) > 0) swapStr(str1, str4);
if (strcmp(str2, str3) > 0) swapStr(str2, str3);
if (strcmp(str2, str4) > 0) swapStr(str2, str4);
if (strcmp(str3, str4) > 0) swapStr(str3, str4);
cout << "從小到大排序:" << endl;
cout << str1 << " " << str2 << " " << str3 << " " << str4 << endl;
return 0;
}
std::string 與 std::vector#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
int main() {
vector<string> v(4);
cout << "請輸入四個字串:";
for (int i = 0; i < 4; ++i) cin >> v[i];
sort(v.begin(), v.end()); // 標準庫排序,O(N log N)
cout << "排序結果:";
for (const auto& s : v) cout << s << ' ';
cout << endl;
return 0;
}
getline)。| 錯誤寫法 | 正確寫法 | 說明 |
|---|---|---|
cin >> str[20] | cin >> str | 陣列名即首地址,>> 會寫入整個字串 |
char str[20] 存中文 | std::string | 中文需 2-4 位元組,char[20] 只能存 6-10 個中文字 |
手寫 swap | std::swap / std::sort | 標準庫經過優化、泛型、異常安全 |
C++ 排序字串,**請直接使用 std::string + std::sort**。若教學要求指標操作,務必修正 cin >> str[20] 為 cin >> str,並確保交換函式正確複製字串內容而非指標值。