从文件C ++读取 [英] Read from a file C++

查看:178
本文介绍了从文件C ++读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我想从VTK文件中读取数据到我的C ++程序。
这里是我的文件通常看起来。



POINTS 2双人



1 2



3 4



POINT_DATA 2



SCALARS压力双重



LOOKUP_TABLE预设



5



6



SCALARS密度双重



LOOKUP_TABLE预设



7



8 b
$ b

我想将数据数据以粗体突出显示在我的C ++程序中,但我不知道如何忽略数据之间的文本行。



更准确地说:我有数组 xp [2],yp [2],pressure [2],density [2] code>



我要放置

  0] = 1 yp [0] = 2 

xp [1] = 3 yp [1] = 4

pressure [0] = 5 pressure [1] = 6

density [0] = 7 density [1] = 8



不知道如何做到这一点,因为有数字之间的文本,我必须放入我的数组。

解决方案

您可以使用 ignore 函数不是数字。使用 cin>> x 从输入文件读取值x。如果失败,则在输入流中设置 failbit ,您必须清除。然后,忽略整行。

  std :: vector< int>数据; 
while(!cin.eof())
{
int x;
if(cin>> x){
data.push_back(x);
if(data.size()== 8)
{
//使用8个数字做任何你想要的操作
data.clear();
}
} else {
cin.clear();
cin.ignore(1000,'\\\
'); //假设最大行长小于1000
}
}

代码假设从 cin 读取,重定向到另一个输入文件)


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 4

POINT_DATA 2

SCALARS pressure double

LOOKUP_TABLE default

5

6

SCALARS density double

LOOKUP_TABLE default

7

8

I want to put the numerical data highlighted in bold into my C++ program but I dont know how to ignore the text lines in between the data.

To be more precise: I have arrays xp[2], yp[2], pressure[2] , density[2]

I want to put

              xp[0]=1 yp[0]=2 

              xp[1]=3  yp[1]=4

              pressure[0]=5 pressure[1]=6

              density[0]=7  density[1]=8

I dont know how to do this since there is text between the numbers that I have to put into my arrays.

解决方案

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<int> 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)

这篇关于从文件C ++读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆