編寫程式從 std::string 物件中移除所有標點符號。輸入必須包含至少一個標點,輸出為移除後的字串;若無標點則報錯。
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string input, result;
bool has_punct = false;
cout << "請輸入一個字串: " << endl;
getline(cin, input);
for (string::size_type i = 0; i != input.size(); ++i) {
char ch = input[i];
if (ispunct(static_cast<unsigned char>(ch))) {
has_punct = true;
} else {
result += ch;
}
}
if (has_punct) {
cout << "結果: " << endl << result << endl;
} else {
cerr << "錯誤: 字串中不包含任何標點符號!" << endl;
return -1;
}
return 0;
}
ispunct:自 <cctype>,判斷字元是否為標點。注意需轉型為 unsigned char 避免負值導致未定義行為。getline:讀取整行含空白的輸入。cerr 並回傳非零值。#include <iostream>
#include <string>
#include <cctype>
#include <algorithm>
int main() {
std::string input;
std::getline(std::cin, input);
std::string result;
result.reserve(input.size());
bool has_punct = false;
std::copy_if(input.begin(), input.end(), std::back_inserter(result),
[&has_punct](unsigned char ch) {
if (std::ispunct(ch)) { has_punct = true; return false; }
return true;
});
if (!has_punct) {
std::cerr << "字串中不包含標點符號!\n";
return 1;
}
std::cout << "結果:\n" << result << '\n';
}
使用 copy_if + Lambda 更具表達力,且 reserve 避免多次重新分配。