我有一个程序,它逐行读取文件内容,将每一行存储到字符串向量中,然后打印向量的内容。在将文件数据读入字符串向量后,我尝试将每一行从字符串转换为uint32类型。文件的每一行都由32位数字组成。输入数据文件(input_file.dat)的示例:
我希望将每个字符串转换为
我的程序目前为:
在我上述的尝试中,在注释“// Iterate through the vector contents”下面的
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位。
std::stoi
及其伙伴们是什么? - Some programmer dudestd::transform
函数。 - Some programmer dude[2147483648, 4294967295]
内? - NathanOliver09732679
。 - MSaltersstd::istream_iterator
直接从文件中复制到整数向量中:std::vector<uint32_t> intVector(std::istream_iterator<uint32_t>(in), std::istream_iterator<uint32_t>());
这就是你需要的全部内容,可以将所有整数从文件读入向量中。 - Some programmer dude