我试图读取一个只有数字的文件,没有空格。我需要在矢量向量中将这些数字设置为四到四。在这里我尝试过并且没有工作因为没有显示任何东西。
vector<vector<int>> vectorReader(string path) {
ifstream file( path );
int i;
char bit;
vector<vector<int>> fle;
vector<int> word;
i = 0;
if(file.is_open()){
while(file >> bit){
if(i % 4 == 0) {
fle.push_back(word);
vector<int> word;
}
else {
word.push_back((bit - 48));
i++;
}
}
}
else{
cout << "Error!.\n\n";
}
fle.erase( fle.begin() );
return fle;
}
int main(){
string path = "file.txt";
vector<vector<int>> file = vectorReader( path );
for(const auto &line : file) {
for(const auto &val : line) {
cout << val;
}
cout << endl;
}
return 0;
}
file.txt的
0110010010100101100111110011111010011011001011100001111110001100101100
预期产出:
0110
0100
1010
0101
1001
1111
答案 0 :(得分:3)
你的逻辑错误而奇怪。这是一个正确的版本:
vector<vector<int>> vectorReader(string path) {
ifstream file(path);
char bit;
vector<vector<int>> vec;
vector<int> word;
int i = 0;
if (file.is_open()) {
while (file >> bit) {
word.push_back((bit - '0')); // add digit in word vector
if (++i % 4 == 0) { // if 4 digits have been added to word vector
vec.push_back(word); // add word to vec vector
word.clear(); // and clear word vector for next iteration
}
}
}
else {
cout << "Error!.\n\n";
}
return vec;
}