gpt4 book ai didi

c++ - 左移运算符在C++中从整数转换为字符串时做了什么

转载 作者:行者123 更新时间:2023-11-28 03:14:56 26 4
gpt4 key购买 nike

假设你想把一个整数转换成字符串这是c++中的方法

    int c1=999;
stringstream ss;
ss<<c1;
string str=ss.str();

在C++中如何转换成字符串? stringstream 包含什么以及上面程序的第 3 行在该语句中,即我的意思是左移运算符(我们知道符号“<<”用于左移)在这里做什么以转换为字符串

最佳答案

要将 int 转换为字符串(非常简单),您必须遍历所有数字,将其转换为常规 char,然后将其放入字符串中:

int toConvert = 999;
string res = "";

while (toConvert)
{
int lastDigit = toConvert % 10; //retrieve last digit
char c = lastDigit + '0'; //translate it to the char corresponding
string reverse(c); //We have to add it in front of the string, or otherwise
reverse.append (res); // the digits will be reversed.
res = reverse;
toConvert /= 10;
}

这是将 int 转换为字符串的一种非常基本的方法,我相信它在运算符“<<”中做得更好,但你明白了。

关于c++ - 左移运算符在C++中从整数转换为字符串时做了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17209168/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com