首页 > 解决方案 > 如何反转我的输入,包括否定

问题描述

这是我目前拥有的代码,但它总是输出 0 我试图让它输出输入的反向,包括负数,例如 -123425 将是 524321-:

#include<iostream>
using namespace std;

int main() {
    int number;
    bool negative;
    cout << "Enter an integer: ";
    cin >> number;
    while (number != 0) {
        number % 10;
        number /= 10;
    }
    if (number < 0) {
        negative = true;
        number = -number;
        cout << number << "-";
    }
    else {
        negative = false;
    }
    cout << number << endl;

    return EXIT_SUCCESS;
}

标签: c++loopsintreverse

解决方案


您可以将输入转换为 a std::string,然后使用 反转其内容std::reverse

#include <algorithm> // reverse
#include <cstdlib>   // EXIT_SUCCESS
#include <iostream>  // cin, cout, endl
#include <string>    // string, to_string

using namespace std;

int main()
{
    cout << "Enter an integer: ";
    int number;
    cin >> number;
    auto str = to_string(number);

    reverse(str.begin(), str.end());
    cout << str << endl;

    return EXIT_SUCCESS;
}

读取int第一个 - 而不是 a std::string- 确保我们从输入中解析一个有效的整数。将其转换为 astd::string允许我们将其反转。-042这让我们可以向程序提供类似and的输入-0,并得到24-and0作为结果,而不是240-and 0-


推荐阅读