c++ char数组转换为int

C++ char array to int

本文关键字:int 转换 数组 char c++      更新时间:2023-10-16

我是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)
);