c++ - 字符串和 double 的问题,等号后得到另一个数字

标签 c++ string char int ostream

计算完一个数后,我需要得到这个数的几位数字。我将其转换为字符串,并打印一个数字,但在一段代码中,它工作正常(仅打印一个数字),但在我将其等于另一个变量后,程序打印 2 位数字。

#include "stdafx.h"
#include <iostream>
#include <chrono>
#include <ctime>    
#include <sstream>

using namespace std;
int main()
{
    time_t seconds;
    int res = 0;
    seconds = time(NULL);
    double nump = seconds;
    cout.precision(45);
    for (int i = 1; i <= 100; i++) {
        nump = nump /10;
    }
    std::ostringstream strs;
    strs.precision(55);
    strs << nump;
    std::string str = strs.str();
    cout << str[str.size() - 9] << endl; // here we get a gidit from the string (e.g. 5)
    res = str[str.size() - 9];
    cout << res << endl; // here we get a number (e.g. 49)
    system("pause");
    return 0;
}

我无法理解发生了什么事。请帮忙!

最佳答案

那是因为这里

res = str[str.size() - 9];

您将 char 的值存储在 int 中。将相同的值发送到 std::cout 时与将其打印为 char 时,将其打印为 int 可能会产生不同的结果。对于整数 this调用运算符,而对于字符 this而是调用运算符。

在您的示例中,您的值可能为 '1'(ASCII 格式为 49)。当您将其打印为 char 时,它会打印 1,而当您将其打印为 int 时,它会打印 49 >.

解决此问题的一种方法是将 int res 改为 char

关于c++ - 字符串和 double 的问题,等号后得到另一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57785558/

相关文章:

Python正则表达式提取字符串末尾的可选数字

string - ResponseWriter.Write 和 io.WriteString 有什么区别?

java - Java NIO中ByteBuffer和CharBuffer有什么区别?

c++ - 无法为 dynamic_cast 确定值的最派生类型

c++ - 坚韧 : Dealing with deeply nested pointers in C++

c++ - 行为根据它所链接的类而改变的程序

c++ - 推荐的旋转组合方式

ios - 字符串到字典和向后

c++ - 为什么将字符串文字传递给 char* 参数有时只是编译器错误?

c - C 中 char 数组的 if 语句