Getting part of string in CSV file and converting to int

I'm trying to do math with some of the information in two different CSV files, using C++. Right now I'm only working with one of them, and I want to find out how to convert part of the file's strings into integers so I can do mathematical operations with them like averaging and such. I'm not able to do this using arrays, vectors, structs, pointers or anything of the like (this is an assignment, we're not allowed to use these things) and every example I've found thus far is using vectors or arrays somehow, or stringstream with "std::" when I already have using namespace std; (we were told to use that). This is my code so far.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  #include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
    string line;
    ifstream myfile ("elect12.csv");
    if (myfile.is_open())
    {
        while ( getline (myfile,line) )
        {
            cout << line << '\n';
        }
        myfile.close();
    }
    
    else cout << "Unable to open file";
    
    return 0;
}


I currently am able to put the whole string out with this code, getting outputs like this:
795696 1255925 22717 2074338 AL
so far, with 50 other lines like it (this is a CSV file with 51 rows and 5 columns, the other is a CSV file with 51 rows and two columns). I'm trying to access separate integers, like for example in this line I'd try to access the first one 795696 and the last 2074338, and do some type of math with those. Please let me know what I can do from here. All help is appreciated, as well as any information on linking two csv files in the same code (I'll need to access both files over and over, multiple passes?).
Last edited on
Assuming the file contents are as so:
795696 1255925 22717 2074338 AL
with each number separated by a whitespace.

You can do this
getline( myfile, line, ' ' )

Then to get that as an int, use atoi.
http://www.cplusplus.com/reference/cstdlib/atoi/
To convert the string to a C-string, simply call c_str( ).
http://www.cplusplus.com/reference/string/string/c_str/
Last edited on
It looks like one of those is a pointer, I can't use that, just checked the assignment again and made edits. Sorry about that.
Last edited on
think about vfscanf to analyze and transform the line

ReadStuff ( pFile, "%d %d %d %d %s ", &val1, &val2, &val3, &val4, s );


http://www.cplusplus.com/reference/cstdio/vfscanf/
Last edited on
Topic archived. No new replies allowed.