所以我是C++向量的新手,我的目标是从文件中读取一行,将其存储在字符串向量中,将其转换为整数并将其推送到 int 向量。我遇到了一个问题,当我将 char 转换为 int 时,我会丢失前导 0。我想保留前导 0(该文件是矩阵文件(。我将最终文件存储在 2D int 矢量中。当我运行 temp.size(( 时,我得到的结果为 1,我知道这与我将字符串转换为整数的方式有关,所以我相信向量中只存储了 1 个数字。
std::vector< std::vector<int> > data;
std::vector< std::vector<int> > res;
std::ifstream f("input.txt", ios::binary);
string line;
int count;
while(std::getline(f,line))
{
std::vector<string> line_data;
std::vector<int> temp;
std::istringstream iss(line);
std::string value;
while(iss >> value)
{
line_data.push_back(value);
std::transform(line_data.begin(), line_data.end(),
std::back_inserter(temp),
[](std::string &s) { return std::stoi(s); } );
count = value.length();
count = count - temp.size(); // temp.size() returns 1, why is that and how can I fix it?
cout << count <<endl;
temp.insert(temp.begin(),count,0);
data.push_back(temp);
}
我的输入是一个未知长度的布尔方阵。 例如:
00101
10101
10100
00101
01111
编辑:
从 int 向量数据获取输出时:
101
10101
10100
101
1111
失去前导0
所以我尝试计算值和温度长度的差异并手动插入 0。
为什么要对文本数据使用二进制模式?稍微简化了一下,所以它来了:
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
int main()
{
std::ifstream f("input.txt");
std::vector< std::vector<int> > data;
std::string line;
// fill data
while (std::getline(f, line))
{
std::vector<int> temp;
std::transform(line.begin(), line.end(),
std::back_inserter(temp),
[](char c) { return std::stoi(std::string(&c, 1)); });
data.push_back(temp);
}
// print data
for (std::vector<int> x : data)
{
for (int y : x)
std::cout << y;
std::cout << std::endl;
}
return 0;
}
指纹:
00101
10101
10100
00101
01111