去除字符串特殊字符程序故障排查:含空格输入仅保留首段内容
Let's break down why your program only outputs the first word, and walk through the fixes step by step.
The Root Cause
The main issue is using cin >> tem to read input. The >> operator stops reading as soon as it hits any whitespace (space, tab, newline). So when you enter "Life is beautiful", tem only captures "Life", and the rest of your input gets stuck in the buffer (your unused cin >> pas line would even read "is" into pas, but that data never gets processed anyway).
Corrected Code
Here's the fixed version that reads the full input line and extracts only letters as intended:
#include <iostream> #include <string> // Use <string> for C++ std::string instead of C-style <string.h> using namespace std; int main() { string mes = ""; string tem; // Read the entire input line, including spaces getline(cin, tem); for (int i = 0; i < tem.length(); i++) { char c = tem[i]; int ch = static_cast<int>(c); // Safer C++-style cast instead of (int)c // Check if character is uppercase (A-Z) or lowercase (a-z) if ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122)) { mes += c; } // Uncomment below if you want to keep spaces instead of removing them // else if (ch == 32) { // mes += c; // } } cout << mes << endl; // Print the final processed string return 0; }
Key Changes Explained
- Replaced
cin >> temwithgetline(cin, tem): This reads the entire input line, spaces included, so every character from your input gets processed in the loop. - Swapped
<string.h>for<string>:<string.h>is for C-style string functions (likestrcpy), while C++'sstd::stringrequires the<string>header. - Removed unused
cin >> pas: This line was siphoning part of your input but not using it, which made the truncation problem worse. - Completed the letter check: The original code cut off mid-condition—we added
<=122to cover all lowercase letters (a-z). - Added output for the result: The original code didn't print the final
messtring, so we addedcout << mes << endl;to show your processed output.
Example Output
If you input "Life is beautiful", the program will output Lifeisbeautiful (since spaces are treated as special characters and removed). If you want to preserve spaces, just uncomment the block that checks for ASCII 32 (space) and adds it to mes.
内容的提问来源于stack exchange,提问作者Abhinandan Vellanki

