开发者

Stream and c++ - parsing file

开发者 https://www.devze.com 2022-12-10 11:38 出处:网络
I did it before... But I forgot. I have a file with some data: 0.5 0.6 0.7 1.2 1.5 How can I read this in c++? I did it with stream... som开发者_开发百科ething like:

I did it before... But I forgot. I have a file with some data:

0.5 0.6 0.7 1.2 1.5

How can I read this in c++? I did it with stream... som开发者_开发百科ething like:

float var = 0;
stream >> var;


The following snippet should give you a clue. Don't forget to include <fstream>.

std::ifstream fin("filename.txt");
float value;
while (fin >> value)
{
    // Do whatever you want with the value
}

Do not try to test fin.eof() it won't tell you if you're about to bump to the end of file.


Something like this?

std::ifstream stream("C:/a.txt");
    float var = 0;
    while(stream >> var)
    {
        //Do some processing
    }


Do you mean how to open a file and read data from it?

That should look something like this:

float var;
ifstream infile("filename");
if(infile.good()){
    while(!infile.eof()){
        infile >> var;
        cout << var << "is the next value\n";
    }
}


To read from files, use std::ifstream.


Something like this. The << operator treats spaces as a separator.

float array[5] = {0.0f};

for(int i = 0; i < 5; i++)
{
    stream >> array[i];
}

BTW I did 5 since you had 5 in your example. (and I am assuming you have the stream setup)

0

精彩评论

暂无评论...
验证码 换一张
取 消