How can I read and process data from a .txt file in c++ ?

Jan 18, 2015 at 8:06pm
Hi guys,

I'm a beginner in c++ and have relatively litle knowledge. So I would like to ask you if somebody can help me with my task. I hace to read data from a .txt file ( 34 columns and a lots of arrows) and then try to find the min, max and mean value from each column.I have tried to use fscaf but it doesn't seem to really work. Thanks in advance for your help

Jan 18, 2015 at 9:30pm
I just helped out someone else that had a similar problem:
http://www.cplusplus.com/forum/beginner/153593/

To read data from a txt file you can use std::fstream
Examples can be found by clicking different function names
http://www.cplusplus.com/reference/fstream/fstream/

For example clicking (constructor) will show you how to create an std::fstream.
http://www.cplusplus.com/reference/fstream/fstream/fstream/

Clicking operator>> will show you how to read data from an fstream
http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/
Last edited on Jan 18, 2015 at 9:31pm
Jan 19, 2015 at 3:22am
1
2
3
4
5
6
7
8
9
10
#include <string>
#include <fstream>

std::ifstream in("myfile.txt");

double input;

while (in >> input){
//do work
}



Sometimes, we have to work line by line in a file.
In such cases std::istringstream is quite helpful. You get a line, and treat that line as a stream.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <string>
#include <fstream>
#include <sstream>


std::ifstream in("myfile.txt");

if (in)
    {
      std::string line;
       while (std::getline(in, line)){
        std::istringstream split(line);
        double val;
        split >> val;
        std::string input;
        split >> input;
       }
     }   

Last edited on Jan 19, 2015 at 3:23am
Topic archived. No new replies allowed.