Hello,
I have task to read the CSV file using C++ , the CSV file contains 10 rows x 3 colums float data and I want to read it and apply some mathematic and then the ouput should be stored in a new matrix. The thing is If can read data then I will apply methamatics by using for loop but Is there anyway of reading the csv file in C++?

I am using Visual studio 2010

any syntax for reading the csv ?

Thanks

Recommended Answers

All 15 Replies

CSV is just a text format, so you'd open and read the file as you would any text file. However, you need to parse the format. For example using a very simple variant of CSV:

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    ifstream in("file.csv");
    vector<vector<double>> fields;

    if (in) {
        string line;

        while (getline(in, line)) {
            stringstream sep(line);
            string field;

            fields.push_back(vector<double>());

            while (getline(sep, field, ',')) {
                fields.back().push_back(stod(field));
            }
        }
    }

    for (auto row : fields) {
        for (auto field : row) {
            cout << field << ' ';
        }

        cout << '\n';
    }
}

Thanks and How to write the file path in program?

I want to use for loop to read the file data and save it in to a Matrix , which contain measurement of 3 Columns

Thanks and How to write the file path in program?

...um, you may want to drop back a bit and study file I/O in C++. I had been operating under the assumption that your problem was parsing the format, not the basics of how to read a file.

Thank you so much for your help , I will revice some concepts and if still I will any difficulty I will as here :)

Thanks DaniWeb

Thanks deceptikon for ur code and Checked it today and it's giving me some error, Can u tell me where I am going wrong

I have this code now

#include <fstream>
#include <iostream>
#include <stdio.h>
#include <conio.h>
using namespace std;

int main() {
   ifstream ifs( "myfile.csv" );       
   if ( ! ifs.is_open() ) {                 
      cout <<" Failed to open" << endl;
   }
   else {
      char word[10];
      ifs>>word;
      while(ifs.good()){
                        cout<<word<< " ";
                        ifs>>word;
                        }
   }
   getchar();
}

Now the problem is that when I run the progarm then ouput just shows black and it says "Not responding, send error report"

When I tried to read the txt file it works good and displays the out whole sentence in the text file

When I open my CSV file in visual studio it convert it into text file with contents separated by commas

Example:

Origianl CSV File Data

1.1 1.2 1.3
2.1 2.2 2.3

The abpve data se 2(rows) x 3(col)

When I open this file in visual stdio (File- Open- opefile- myfile.txt)

the csv file data is like

1.1,1.2,1.3
2.1,2.2,2.3

So let say if my compiler is not reading the csv file I can just convert it in to text and then read it via my program but how to store the element in 10 x 3 Matrix vector that after reading line it store the first content and then second conten which is after comman and then the third, then it go to second line and does the same for that too

Thanks deceptikon for ur code and Checked it today and it's giving me some error, Can u tell me where I am going wrong

I have this code now

#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <stdio.h>
using namespace std;
int main(){
    float r[3][10];
    int i,j;
    ifstream infile("my.txt"); 
    string line = "";
    while (getline(infile, line)){
        stringstream strstr(line);
        float num = "";
        while (getline(float,num, ' ')) 
              {
              for(i=1; i<=10; i++)
              {
                       for(j=1; j<=3; j++){
                                r[i][j]=num;
                                printf("%f",r[i][j]);
                                }
                       printf("\n");
                       }

              }
    }
getchar();
}

When I run it it shows the junk values in the float variable.

Now the above program is for reading the data from file and when ' ' (Space) come for loop starts and store the variable in r, but in ouput it's showing junk values can anyone tell me where I am going wrong ?

Thanks deceptikon for ur code and Checked it today and it's giving me some error, Can u tell me where I am going wrong

You're probably not using a compiler that supports C++11, or compiling with that switch disabled. However, I can't tell you what's wrong when you don't tell me what the errors are. :rolleyes:

Why are you looking for spaces in a csv file? csv stands for comma seperated values. Your file should look like

1.1,1.2,1.3
2.1,2.2,2.3
...

@ deceptikon: My Program was giving too many errors for the data type , My file contains the float values while I was assigning string to the variable. So leave that :P

I have this shortest code available :

#include <iostream>
#include <string>
#include <fstream>
#include <stdio.h>
int main()
{
    using namespace std;

    ifstream file("my.csv");
    if(file.is_open())
    {
        float r[10][3];

        for(int i = 0; i < 10; ++i)
        {
            for(int j = 0; j < 3; ++j)
            {
            file >> r[i][j];
            printf("%f\n",r[i][j]);
            }
        }

    }


getchar();
}

Since visual studio was giving so many errors so I started working on Dev C++ and that's why It wasn't reading CSV file , this code reads the CSV file in visual studio , Now I am wrong at a point that when a comma come then loop should work Like " while (getline(strstr,word, ',')) " in my previous program
Can you tell me how to fix this ?

@NathanOliver: Thanks for the Info (Y), Actually csv file was opened by outlook at my laptop so I thought it to be an Office file :D

#include <iostream>
#include <string>
#include <fstream>

int main()
{
    using namespace std;

    const int rows = 4;
    const int cols = 3;

    ifstream file("test.txt");

    if (file.is_open()) {
        float r[rows][cols];

        for (int i = 0; i < rows; ++i) {
            for (int j = 0; j < cols; ++j) {
                file >> r[i][j];
                file.get(); // Throw away the comma
            }
        }

        for (int i = 0; i < rows; ++i) {
            for (int j = 0; j < cols; ++j) {
                cout << r[i][j] << ' ';
            }

            cout << '\n';
        }
    }
}

Thanks SO much deceptikon (Y)
Check ur Inbox

EDIT : I have this code:

#include <iostream>
#include <string>
#include <fstream>
#include <stdio.h>
#include <math.h>

using namespace std;


// Task 1 part
struct pairtickle { int x, y; };
/**
    Generates a random particle given the upper bound
    of each coordinate. The lower bound is always 0.
*/
struct pairtickle random_particle(int x_max, int y_max)
{
    struct pairtickle result;
    result.x = rand() % x_max;
    result.y = rand() % y_max;
    return result;
}
//Task 1 part


// refrence vector Initialization and Storage
int main()
{
// Task 1 part
    struct pairtickle particles[300];
    int k;
    /* Generate the 300 random particles */
    for (k = 0; k < 300; k++) {
        particles[k] = random_particle(20, 20);
    }
    /* Display them */
    /*for (k = 0; k < 300; k++) {
        printf("(%d,%d)\n", particles[k].x, particles[k].y);
    }*/

    //Task 1 part


    struct mat { 
    int x[3];
    int y[3];
    }r1;
    int a,b;
    for (a=0; a<=1; a++)
      {
        for (b=1; b>=0; b--)
           {   
               r1.x[a]=a;
               r1.y[b]=b;
               printf("(rx,ry)=(%d,%d)\n", r1.x[a], r1.y[b]);
            }
      }
            printf("\n \n \n");

    // reading csv file and storing values in matrix r 
    const int rows = 10;
    const int cols = 3;
    ifstream file("my.txt");
    if (file.is_open()) {
        float r[rows][cols];
        for (int i = 0; i < rows; ++i) {  // Reading Data from File
            for (int j = 0; j < cols; ++j) {
                file >> r[i][j];
                file.get(); // Throw away the comma
            }
        }
        for (int i = 0; i < rows; ++i) { // Printing the File data
            for (int j = 0; j < cols; ++j) {
                cout << r[i][j] << ' ';

            }
            cout << '\n';
        }
         // Generation of Matrix W Start
         const float pi = 3.1415927;
         double w[10][3][300];
         double w1[10][3][300];
    for (int i=0; i<10; i++)
    {
        for (int j=0; j<3; j++)
        {
            for (int k=0; k<300; k++)
            {
                w[i][j][k]= ((particles[k].x + r1.x[j]) + (particles[k].y + r1.y[j])) - ((particles[k].x + r1.x[j+1]) + (particles[k].y + r1.y[j+1]))- r[j][k];
                w1[i][j][k]=(1/sqrt(4*pi))*exp(-pow(w[i][j][k],2)/(4));
                printf("%lf\n",w1[i][j][k]);
                }
                }
                }
                // Generation of Matrix W End
    }





    getchar();
}

I want to apply Summation (Σ) on w1[i][j][k] with lower limit of j and upper limt of j-1.

OK Now I added

float sum_w;
sum_w +=w1[i][j][k];
printf("Sum= %f",sum_w);

I added sum_w +=w1[i][j][k]; just after the w1 part in my code. The problem is when I run the code Ouput gives me this :

Sum = -1.#QNANO

When I limit 'k' to 92 in for loop then it gives the float value .

What's that ?
I also read Khan Summation Algo : http://en.wikipedia.org/wiki/Kahan_summation_algorithm

But it's difficult, Can anyone guide me the easy way of doing that

hello,
the fstream is used for c++ what is there any possiblity of reading the csv file with 10 rows and 3 columns using C ?

@deceptikon I just wanted to say thank you so much for posting this code!! It saved me a lot of time, and I learned a lot by going through your code. :-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.