将标准输出重定向为整数
Redirecting standard output to integer
我正在解决以下问题:反转整数的数字。现在,该问题的代码很简单。
void reverse(int x){
if(x < 0){
cout << "-";
x*=(-1);
}
while(x!=0){
cout << x%10;
x/=10;
}
}
但是问题要求将答案作为整数返回。所以我想知道是否有任何方法可以将输出流重定向到整数。我知道我可以将其重定向到字符串,然后转换为整数。但是有什么直接的方法吗?
与其使用 cout
直接显示结果,不如尝试将结果存储到变量中,例如 rev
并返回结果。
int reverse(int x)
{
bool neg = x < 0;
int rev = 0;
while (x != 0) {
rev = (rev * 10) + (x % 10);
x /= 10;
}
return neg ? -rev : rev;
}
您可以使用 std::ostringstream
,保存缓冲区std::cout
然后将其转换为 int:
void reverse(int x)
{
std::ostringstream local_buffer;
auto old_buff = std::cout.rdbuf(local_buffer.rdbuf()); // save pointer to std::cout buffer
if(x < 0){
std::cout << "-";
x*=(-1);
}
while(x!=0){
std::cout << x%10;
x/=10;
}
std::cout.rdbuf(old_buff); // back to old buffer
int rev = std::atoi(local_buffer.str().c_str());
std::cout << "rev is: " << rev << "n";
}
科里鲁在线
为什么不创建一个返回 int 的函数?
#include <cmath> // needed for pow()
int reverse(int x)
{
int y=0;
int numDigits=0;
int x2=x;
// first count number of digits
while(x2!=0){
x2/=10;
numDigits++;
}
// then do the reversion by adding up in reverse direction
for(int i=0; i<numDigits; i++){
y+=(x%10)*pow(10,numDigits-i-1);
x/=10;
}
return y;
}
您可以将其转换为字符串,然后向后将其发送到字符串流。
std::stringstream s;
std::string s = std::to_string(x);
for (std::string::reverse_iterator rit = s.rbegin(); rit != s.rend(); ++rit) {
std::cout << *rit;
ss << *rit;
}
std::cout << std::endl;
return stoi(ss.str());
加
#include <sstream>
我运行了int和string版本2.5工厂。 循环次数,字符串版本在我的MacBook Pro 2012上的速度是其两倍。 1.2秒与2.4秒 要考虑使用字符串的东西,即使它可能很少使用。
更新:
另一个 SO 答案建议 std::反向,当我将代码更新为
auto s = std::to_string(x);
std::reverse(s.begin(), s.end());
return stoi(s);
它使用0.8秒,比交换数字快三倍。
相关文章:
- 如何将stdout重定向到stderr
- 编写时C++中的输入重定向问题
- 获取通过重定向传入的输入文件的名称?
- Windows C++重定向库
- 写入文件 a.txt,而终端重定向到文件 b.txt
- 使用 dup2() 进行输入重定向
- 将 clangd stderr 重定向到文件而不是控制台
- 如何在C++中获取重定向网页的URL
- 将标准输出重定向到ostream
- 如何撤消此代码上的 cin 重定向?
- 使用重定向标准处理子进程中的 kbhit
- 是否可以将子进程的 stdout 重定向到父进程中的另一个文件?
- 重定向输入和输出时如何处理主文件I/O?
- 如何将HTTPS流量重定向到本地主机:443上的代理?
- 使用重定向命令从 stdin 读入的字符串"<"输入文件未正确附加
- 如何将输入重定向与特殊整数作为分隔线和直至EOF
- 输入重定向读取整数和char C
- 如何在 c++ 中使用输入重定向添加整数
- C++ - 使用 IO 重定向输入和输出多个整数
- 将标准输出重定向为整数