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

如何检测用户输入是否以0开头?为C++数字反转程序添加首字符为0的错误提示的最简方案

Nice question! The problem with your current code is that when you read input directly into an int, leading zeros get dropped automatically—since integers don’t store leading zeros as part of their value. So to catch those cases, we need to first handle the input as a string, which lets us see the exact characters the user typed.

Here’s the simplest way to add the leading zero check and error message:

Quick Fix Breakdown

  1. Read input as a string first: This preserves the user’s exact input, so we can check for leading zeros before converting to an integer.
  2. Validate the string: If the string is longer than 1 character and starts with '0', throw an error. (We let single 0 slide because reversing 0 is just 0, which is valid.)
  3. Convert valid strings to integers: Once we’ve confirmed no invalid leading zeros, turn the string into an int to run your reversal logic.

Updated Working Code

#include<iostream>
#include<string>
#include<stdexcept>
using namespace std;

int main () {
    char choice;
    do {
        string input_str;
        int num, original_num, remainder, reversed_num = 0;
        cout << "Enter a number that you would like to reverse: ";
        cin >> input_str;

        // Check for invalid leading zeros
        if (input_str.size() > 1 && input_str[0] == '0') {
            cout << "Error: Numbers starting with 0 (like 0175) are not allowed.\n";
            goto repeat_prompt; // Skip to asking if user wants another go
        }

        // Make sure the input is actually a valid integer
        try {
            num = stoi(input_str);
            original_num = num;
        } catch (const invalid_argument&) {
            cout << "Error: Please enter a valid whole number.\n";
            goto repeat_prompt;
        } catch (const out_of_range&) {
            cout << "Error: That number is too big for us to handle.\n";
            goto repeat_prompt;
        }

        // Original reversal logic
        while (num != 0) {
            remainder = num % 10;
            reversed_num = reversed_num * 10 + remainder;
            num = num / 10;
        }
        cout << "The reverse of " << original_num << " is " << reversed_num << endl;

        repeat_prompt:
        cout << "Would you like to reverse another number? (Y/N) ";
        cin >> choice;
    } while (choice == 'y' || choice == 'Y');
    cout << "Thanks for using this program!";
    return 0;
}

Why This Works

  • String Input: By grabbing the input as a string first, we can directly inspect the first character—no tricks needed.
  • Leading Zero Check: The condition input_str.size() > 1 && input_str[0] == '0' ensures we only block inputs like 0175, not the valid single 0.
  • Robustness: The try-catch blocks handle cases where the user types letters or super large numbers, so your program won’t crash unexpectedly.
  • Clean Flow: Using goto here is totally acceptable—it lets us skip the reversal logic cleanly when validation fails, without nesting a bunch of conditionals.

If you’re not a fan of goto, you could use a boolean flag (like bool is_valid = true) and wrap the reversal logic in an if (is_valid) block, but goto keeps the code simpler here.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 21:12:27