c++ - 如何反转我的输入,包括否定
问题描述
这是我目前拥有的代码,但它总是输出 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;
}
解决方案
您可以将输入转换为 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-
。
推荐阅读
- android - Android Kotlin:在显示 Snackbar 之前检查视图是否不为空
- typescript - 类型基于 Typescript 中的字符串派生
- laravel - 使用 Laravel 分页和 Bootstrap-vue 分页
- css - 如何在tailwind.css中使用:not()?
- dataframe - 如何在使用 Spark Java 将 Spark Dataframe 写入 Kafka Producer 时控制记录数
- java - 模块化 = true 和 GenericApplicationContextFactory 的 Spring Batch 很麻烦
- javascript - 无法从输入类型文件的 onChange 事件中获取绝对文件名
- excel - SUMPRODUCT 与列上的计算标准
- python - MIDI 刻度是固定值还是取决于文件的 BPM?
- python - 格式不同时如何用re返回字符串?