如何将字符串转换为uint32_t类型

7
我有一个程序,它逐行读取文件内容,将每一行存储到字符串向量中,然后打印向量的内容。在将文件数据读入字符串向量后,我尝试将每一行从字符串转换为uint32类型。文件的每一行都由32位数字组成。输入数据文件(input_file.dat)的示例:
31401402
67662718
74620743
54690001
14530874
13263047
84662943
09732679
13839873

我希望将每个字符串转换为uint32_t,以备用于我编写的另一个程序,该程序将这些数字转换为ASCII格式(该程序需要使用uint32_t进行转换)。
我的程序目前为:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

/*
 * Program to iterate through all lines in file and put them in given vector
 *
 */
bool getFileContent(std::string fileName, std::vector<std::string> & vecOfStrs)
{

    // Open the File
    std::ifstream in(fileName.c_str());

    // Check if object is valid
    if(!in)
    {
        std::cerr << "Cannot open the File : "<<fileName<<std::endl;
        return false;
    }

    std::string str;
    // Read the next line from File untill it reaches the end.
    while (std::getline(in, str))
    {
        // Line contains string of length > 0 then save it in vector
        if(str.size() > 0)
            vecOfStrs.push_back(str);
    }
    //Close The File
    in.close();
    return true;
}


int main()
{
    //Store contents in this vector of strings
    std::vector<std::string> vecOfStr;

    // Get the contents of file in a vector
    bool result = getFileContent("input_file.dat", vecOfStr);

    // If above result is true
    if(result)
    {
        // Iterate through the vector contents
        for(std::string & line : vecOfStr)
        {
            //std::cout<<line<<std::endl;      Ignore this print line, it is for debugging only to show that the vector has been correctly filled

            //For each line, convert from string to uint32_t
            std::vector<std::uint32_t>new_variable
            new_variable.assign(vecOfStr.begin(), vecOfStr.end());

        }
    }
}

在我上述的尝试中,在注释“// Iterate through the vector contents”下面的for循环中,我尝试使用vector::assign函数将每一行从string转换为uint32_t。我在研究我的问题时做了这个尝试,并从另一个SO问题中找到了这个函数:fastest way to convert a std::vector to another std::vector (作者:Vlad,于2011年10月26日7:36回答)。当我尝试运行此代码时,我收到以下error消息:
error: cannot convert ‘std::__cxx11::basic_string<char>’ to ‘unsigned int’ in initialization

总结:

如何逐行读取文件内容,将每行转换为数据类型uint32_t?我已确保每行都等于32位。


4
std::stoi及其伙伴们是什么? - Some programmer dude
1
要将字符串向量转换为整数向量,可以使用std::transform函数。 - Some programmer dude
1
那么文件中的所有数字都在范围 [2147483648, 4294967295] 内? - NathanOliver
1
@NathanOliver:该示例包括09732679 - MSalters
1
在我看来,最简单的方法是根本不必使用字符串向量,而是像上面提到的那样使用std::istream_iterator直接从文件中复制到整数向量中:std::vector<uint32_t> intVector(std::istream_iterator<uint32_t>(in), std::istream_iterator<uint32_t>()); 这就是你需要的全部内容,可以将所有整数从文件读入向量中。 - Some programmer dude
显示剩余6条评论
2个回答

8

像这样

std::vector<std::uint32_t> new_variable;
for (string str : vecOfStr)
    new_variable.push_back(static_cast<uint32_t>(std::stoul(str)));
stoul函数将字符串转换为整数。严格来说,它将其转换为一个unsigned long而不是uint32_t。但是,uint32_t的所有合法值都可以由unsigned long表示,并且使用转换可以将其转回到您想要的uint32_t
还有其他方法(例如使用std::transform),但我发现显式循环更简单。
上面的代码没有错误检查。如果需要这样的检查,则最好使用artm的答案。
顺便说一句,您的尝试失败是因为stringuint32_t之间没有隐式转换。当存在隐式转换时,您尝试的方法将起作用。

2
uint32_t > int32_t. 这样会存在溢出问题。 - NathanOliver
1
已经修复了,希望现在没问题了。 - john
1
不需要强制类型转换,但使用它肯定更好。 - NathanOliver
2
@NathanOliver 警告,我讨厌警告。 - john
4
一个小建议:for (string str : vecOfStr) -> for (string const& str : vecOfStr),以避免复制。 - NathanOliver
1
为了更易于维护,请使用以下代码:for(auto const& str : vecOfStr) - acegs

0

使用 stringstream 进行格式化,需要包含头文件 <stringstream>

另外:

  • new_variable 移到循环外,否则生成的 vector 将没有用处。

  • 不需要将 vecOfStrs 作为引用传递。最好通过值返回 vector

        std::vector<std::uint32_t> new_variable;

        for(std::string & line : vecOfStr)
        {
            //For each line, convert from string to uint32_t

            std::stringstream ss(line);
            uint32_t val;
            if( !( ss >> val ) )
            {
                throw std::runtime_error( "failed to convert to uint32" );
            }
            
            std::cout << "val = " << val << '\n';   
            new_variable.push_back( val );
        }

2
或许向量声明应该放在循环外面。 - Ari0nhh
1
原始代码,但是是的,否则它在循环之外就没有任何用处。 - artm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接