将字符转换为字符串
convert char to string
你好?我想知道"如何将字符转换为字符串"
这是我的 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.";
相关文章:
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 如何将这个std::字符串转换为std::基本字符串
- 如何正确将字符串转换为标准::时间::system_clock::time_point?
- 如何在C++中将十六进制字符串转换为文本数据
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 如何从字符串转换为双精度*
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- 如何在C++中将 Python 字符串转换为其转义版本?
- 如何在 C++11 中将标准::字符串转换为标准::u32字符串?
- 如何将整数字符串转换为整数的二维向量?
- 使用 "stringstream " 将字符串转换为整数
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- 将文件复制到自定义位置,存在字符串转换问题
- 将ANSI C字符串转换为UNICODE
- 如何将节点 V8 字符串转换为 C++ 字符串
- 在C++中将字符串转换为双精度,而无需科学记数法
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- 如何在C++中将字符串转换为双精度?
- 将字符串转换为无符号字符数组/字节数组