将字符转换为字符串

convert char to string

本文关键字:字符串 转换 字符      更新时间:2023-10-16

你好?我想知道"如何将字符转换为字符串"

这是我的 C 代码

    string firSen;
    int comma1=0;
    cout<<"Please write your sentence"<<endl;
    getline(cin,first);
    int a=firSen.first("string");
    for(i=a;firSen[i] != ',';i++)
        comma1=i;
    cout<<firSen[comma1-3]<<firSen[comma1-2]<<firSen[comma1-1]<<endl;

我会写"字符串是 100s,谢谢"

我知道 firSen[逗号1-3]=1, firSen[逗号1-2]=0, firSen[逗号1-1]=0 对于字符类型。

我想把这些字符放在字符串中(像 1,0,0 变成 100 的字符串)因为我想使用 atoi 函数....

你知道如何将字符转换为字符串吗?

您可以使用

std::istringstream而不是atoi。像这样:

std::istringstream ss(firSen.substr(comma1-3)); int val; ss >> val;

在这种情况下,如果您知道所需的位置和长度,则可以提取一个子字符串:

std::string number(firSen, comma1-3, 3);

并使用 C++11 转换函数将其转换为整数类型:

int n = std::stoi(number);

或者,从历史上看,字符串流:

int n;
std::stringstream ss(number);
ss >> n;

或者,如果你想成为真正的老派,C 库

int n = std::atoi(number.c_str());

还有其他构建字符串的方法。您可以从字符列表中初始化它:

std::string number {char1, char2, char3};

您可以附加字符和其他字符串:

std::string hello = "Hello";
hello += ',';
hello += ' ';
hello += "world!";

或者使用字符串流,它也可以格式化数字和其他类型:

std::stringstream sentence;
sentence << "The string is " << 100 << ", thank you.";