You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

去除字符串特殊字符程序故障排查:含空格输入仅保留首段内容

Fixing Your C++ Program That Truncates Input After the First Space

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 >> tem with getline(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 (like strcpy), while C++'s std::string requires 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 <=122 to cover all lowercase letters (a-z).
  • Added output for the result: The original code didn't print the final mes string, so we added cout << 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:06:29