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

C++如何实现多单词输入并将全部内容转换为大写输出

问题原因

你当前代码的输入校验逻辑把空格判定为了非法字符:空格的ASCII码值为32,小于'A'的ASCII码值65,会命中else if (ch < 'A' || ch > 'z')的判定,导致all_alpha被置为0,触发输入错误提示。同时原逻辑还存在漏洞,会把ASCII码在'Z'和'a'之间的非字母字符(比如[、\、^等)误判为合法字符。

修改方案

在校验逻辑中额外排除空格的情况即可,仅当字符既不是字母也不是空格时,才判定为非法输入。如果后续需要支持其他合法分隔符(比如英文连字符、所有格单引号等),也可以在校验逻辑中同步添加排除规则。

修改后完整代码

#include <iostream>
#include <stdio.h>
#include <string>

using std::cout;
using std::endl;
using std::cin;

int main() {
    int i, all_alpha;
    char ch, str[100];
    cout << "Enter a word/s: ";
    cin.getline(str,sizeof(str));

    while (1) {
        all_alpha = 1;
        for (i = 0; str[i]; ++i) {
            ch = str[i];
            if (ch >= 'a' && ch <= 'z') { 
                ch = ch - 'a' + 'A';
            } 
            // 仅当字符既不是空格也不是字母时判定为非法
            else if (ch != ' ' && !(ch >= 'A' && ch <= 'Z')) {
                all_alpha = 0;
            }
            str[i] = ch;
        }

        if (all_alpha) {
            cout << str << endl;
            break;
        } else {
            cout << "Sorry, that is a wrong input\n";
            cout << "Enter a word/s: ";
            cin.getline(str,sizeof(str));
        }   
    }
    return 0;
}

内容的提问来源于stack exchange,提问作者DutyRover

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 05:27:03