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

问题描述 投票:1回答:3

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

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;
    }
}

关于解决此问题的任何建议都将大有帮助。

c++ file-io fstream iostream
3个回答
0
投票

通过在while循环周围更改来解决。

while (!inputFile.eof()) {

    inputFile >> currentInput;

    vec2.push_back(currentInput);

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

我很难找到下一行。通过使用peek函数查找'\ n',可以解决此问题。


0
投票

同时(!inputFile.eof(0)){

inputFile >> currentInput;

vec2.push_back(currentInput);

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

} 4679 \


0
投票

我已经使用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 ]
© www.soinside.com 2019 - 2024. All rights reserved.