用c++打印文件的第n列

print out the nth column of a file in c++

本文关键字:文件 c++ 打印      更新时间:2023-10-16

我正在尝试编写一个程序,读取文件的任意列:

#include <iostream>
#include <limits>
#include <fstream>
#include <cstdlib>
int main(int argc, const char * argv[])
{
    std::ifstream in_file("/tmp/testfile");
    int n_skip = 2;
    std::string tmpword;
    while (in_file) {
        if(n_skip < 0) {
            throw "Column number must be >= 1!";
        }
        // skip words
        while(n_skip > 0) {
            in_file >> tmpword;
            n_skip--;
        }
        in_file >> tmpword;
        std::cout << tmpword << "n";
        in_file.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
    }
    return 0;
}

但是它总是打印第一列,为什么?

第一次执行外部while循环时,n_skip设置为2。但是,当执行

时,
    while(n_skip > 0) {
        in_file >> tmpword;
        n_skip--;
    }

n_skip被设置为0,永远不会重置为2。

添加一行

n_skip = 2;

行之后
    in_file.ignore(std::numeric_limits<std::streamsize>::max(), 'n');

我明白了,我需要在每行上恢复n_skip的值:

#include <iostream>
#include <limits>
#include <fstream>
#include <cstdlib>
int main(int argc, const char * argv[])
{
    std::ifstream in_file("/tmp/testfile");
    int n_skip = 2;
    if(n_skip < 0) {
        throw "Column number must be >= 1!";
    }
    std::string tmpword;
    while (in_file) {
        int n_skip_copy = n_skip;
        // skip words
        while(n_skip_copy > 0) {
            in_file >> tmpword;
            n_skip_copy--;
        }
        in_file >> tmpword;
        std::cout << tmpword << "n";
        in_file.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
    }
    return 0;
}