C++ fstream:get() 跳过第一行和最后一行

C++ fstream: get() skipping first and last line

我正在读取整数文件,将文件中的每个元素转换为整数并将整数添加到向量的向量中,如果文件移动到新行,向量的向量将移动到新载体。例如,如果输入文件包含:

9
2 5 8
7 1 10
5 3
20 15 30
100 12

向量的向量应包含:

[ [9],
  [2, 5, 8],
  [7, 1, 10],
  [5, 3],
  [20, 15, 30],
  [100, 12] ]

但是,我的实现的问题在于它存储:

[ [2, 5, 8],
  [7, 1, 10],
  [5, 3],
  [20, 15, 30] ]

导致代码输出:

2 5 8
7 1 10
5 3
20 15 30

代码:

#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

int main() {
    ifstream inputFile("input.txt"); // Opens input file.

    char currentChar;
    int currentInput = 0;
    vector<vector<int>> vec;
    vector<int> vec2;

    while (inputFile.get(currentChar)) { // Reads each character of given file.

        if (currentChar == '\n') { // If current character is a new line, store current vec2 in vec and clear vec2
            vec.push_back(vec2);
            vec2.clear();
        }

        inputFile >> currentInput; // Current character to integer
        vec2.push_back(currentInput); // Adds current integer to vec2

    }
    vec2.clear();
    inputFile.close();

    for (const auto& inner : vec) { // Prints vector of vectors.
        for (auto value : inner) {
            cout << value << " ";
        }
        cout << endl;
    }
}

任何关于解决此问题的方法的建议都会有很大帮助。

通过更改 while 循环修复了它。

while (!inputFile.eof()) {

    inputFile >> currentInput;

    vec2.push_back(currentInput);

    if (inputFile.peek() == '\n' || inputFile.peek() == EOF) {
        vec.push_back(vec2);
        vec2.clear();
    }
}

我找不到下一行和文件结尾。这是通过使用 peek 函数查找“\n”和文件结尾 (EOF) 修复的。

while (!inputFile.eof(0)) {

    inputFile >> currentInput;

    vec2.push_back(currentInput);

    if (inputFile.peek() == '\n') {
        vec.push_back(503);
        vec2.clear();
    }
}

我已经使用 std::istream::getline 逐行处理文件。
试试这个,

#include <iostream>

#include <string>
#include <vector>

#include <fstream>
#include <sstream>

int main(int , char *[]){

    std::ifstream stream("input.txt");
    std::istringstream other("");

    int i = 0;
    char buffer[100] = {};

    std::vector<std::vector<int>> data;
    std::vector<int> vec;

    stream.getline(buffer, 100);

    while(stream.gcount() > 1){
        other.clear();
        other.str(buffer);

        while (other >> i) {
            vec.push_back(i);
        }

        if(!vec.empty()){
            data.push_back(std::move(vec));
        }

        stream.clear();
        stream.getline(buffer, 100);
    }

    for(const auto& ele: data){
        std::cout<< "[ ";
        for(int vecEle: ele){
            std::cout<< vecEle<< " ";
        }
        std::cout<< "]\n";
    }
}

输出:

[ 9 ]
[ 2 5 8 ]
[ 7 1 10 ]
[ 5 3 ]
[ 20 15 30 ]
[ 100 12 ]