c++ char数组转换为int
C++ char array to int
我是c++新手,我正在创建一个小程序。其中一部分我创建了一种将字符数组转换为整型数组的方法。但我只是想知道是否有更好的方法(更有效和/或使用更好的c++标准)。例如,在数组的拼接部分使用atoi为每个数字等。
所以我开始读一组数字,例如:"11 2 123 44"从一个文件转换成一个char *数组,现在想要将它们转换成它们各自的值,当前执行如下操作:
//char * char_cipher; //{'1', '1', ' ', '2', ... , '4'}
//int length; //length of char_cipher
string s = "";
vector<int> cipher_int;
for (int i = 0; i <= length; i++) {
if (char_cipher[i] == ' ') {
//create num
cipher_int.push_back(stoi(s));
s = ""; //empty num
}
else {
//add to string
s += char_cipher[i];
}
}
任何帮助都将非常感激,谢谢:)
您的代码非常接近。问题是你永远不会把char_cipher
的最后一个数字推到cipher_int
上,因为它后面没有空格。你需要在循环完成后做一个额外的检查。
for (int i = 0; i <= length; i++) {
if (char_cipher[i] == ' ') {
//create num
cipher_int.push_back(stoi(s));
s = ""; //empty num
}
else {
//add to string
s += char_cipher[i];
}
}
if (s != "") {
cipher_int.push(back(stoi(s));
}
让STL为您进行解析。您可以使用std::istringstream
,例如:
#include <string>
#include <sstream>
#include <vector>
std::string str_cipher; //"11 2 123 44"
std::vector<int> cipher_int;
std::istringstream iss(str_cipher);
int num;
while (iss >> num) {
cipher_int.push_back(num);
}
另外:
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <iterator>
std::string str_cipher; //"11 2 123 44"
std::vector<int> cipher_int;
std::istringstream iss(str_cipher);
std::copy(
std::istream_iterator<int>(iss),
std::istream_iterator<int>(),
std::back_inserter(cipher_int)
);
相关文章:
- 是否可以从int转换为enum类类型
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 是什么导致了这种使用三进制而不是短整型的有符号int到无符号int转换
- 将字符串中的 int 转换为字母;
- 主.cpp:18:20:错误:从"int*"转换为"int"会失去精度 [-fa
- 将非常大的 int 转换为双倍,在某些计算机上会损失精度
- 如何将矢量<int>转换为字符数组?
- C++ 无法从 const int* 转换为 const_iterator
- 我不断收到错误 C2440'=':无法从"int *(__cdecl *)(int *,int *,int,int)"转换为"int *
- 如何将 int[4] 转换为 std::array<int,4>?
- 如何将data[i].int转换为vaible
- 将 int 转换为字符串,然后连接另一个变量以创建完整扩展名,然后将其转换为 const_char*
- 将私有矩阵形式 int 转换为双 C++
- 无法将参数 1 从 'int' 转换为 'int &'
- 将 int 转换为字符串后始终得到 0
- isspace 函数的性能警告,从 int 转换为布尔值
- 将大 int 转换为浮点数,而不舍入 c++
- 错误:无法将'uint8* {aka unsigned int*}'转换为"常量emxArray_uint8_T*"?
- 将未签名的INT转换为BCD
- 在 C++ 中将 int 转换为双精度