C++字符数组到int 我是C++新手,我正在创建一个小程序。我创建了一种将字符数组转换为int集的方法。但我只是想知道是否有更好的方法更有效和/或使用更好的C++标准。例如,对于etc的每个数字,在阵列的拼接部分使用atoi

C++字符数组到int 我是C++新手,我正在创建一个小程序。我创建了一种将字符数组转换为int集的方法。但我只是想知道是否有更好的方法更有效和/或使用更好的C++标准。例如,对于etc的每个数字,在阵列的拼接部分使用atoi,c++,arrays,C++,Arrays,因此,我开始将一组数字(例如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 <= len

因此,我开始将一组数字(例如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\u cipher中的最后一个数字推送到cipher\u 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->ints具有误导性,我可能标记了错误的副本。无论如何,阅读第二个答案。请务必为此使用std::istringstream。然后扔掉那个字符*。为什么它不是std::string?我甚至需要if语句吗?当然可以只做回推,因为它只包含序列中的最后一个数字。如果字符串以空格结尾,则您已经推送了最后一个数字,而s将包含一个空字符串。因此,目前我正在使用以下方法读取文件。结合你提到的方法,有没有更好的阅读方法?Thanks@austinx43如果文件是使用istream(如ifstream)读取的,那么您可以简单地将该istream原样与运算符>>或istream_迭代器一起使用,而不使用单独的istream。如果看不到代码的其余部分或实际的文件内容,很难告诉您什么是最好的。