Read from a file C++

前端 未结 3 1311
猫巷女王i
猫巷女王i 2021-01-07 10:40

Hi I want to read data from a VTK file into my C++ program. Here is how my files will typically look.

POINTS 2 double

1 2

3条回答
  •  太阳男子
    2021-01-07 11:36

    You can use the ignore function to throw away lines of text that are not numbers. Use cin >> x to read a value x from the input file. If that fails, the failbit is set in the input stream, which you must clear. Then, ignore the whole line.

    std::vector data;
    while (!cin.eof())
    {
        int x;
        if (cin >> x) {
            data.push_back(x);
            if (data.size() == 8)
            {
                // do whatever you need with the 8 numbers
                data.clear();
            }
        } else {
            cin.clear();
            cin.ignore(1000, '\n'); // assuming maximum line length less than 1000
        }
    }
    

    (This code assumes reading from cin, which is redirected to another input file)

提交回复
热议问题