Reading from file using getline()

Hi,
i got a file (teams.csv) which has the following content:
id,name
501,Abilene Chr
502,Air Force
503,Akron
504,Alabama

Now i want to read line by line using getline(). How will i do that?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <fstream> //really needed
#include <string> //really needed
#include <vector> //really needed
#include <sstream> //string to sstream, line 18
#include <iostream> //cout, line 24
int main()
{
    std::ifstream file("teams.csv");
    std::vector<std::string> filecontent;
    std::string rdstr;
    while(std::getline(file,rdstr,'\n')) //while there still data, until '\n'
    if(!rdstr.empty()) filecontent.push_back(rdstr); //if it wasn't an '\n', add to the array
    //Use the info written in filecontent as you want. Now, one new use of getline:
    std::vector<std::vector<std::string>> file_by_comma;
    for(auto a : filecontent) //c++11
    {
        std::vector<std::string> temp;
        std::istringstream c (a);
        while(std::getline(c , rdstr, ',')) //get all words separeted by ','
        if(!rdstr.empty()) temp.push_back(rdstr);
        file_by_comma.push_back(temp);
    }
    for(auto a : file_by_comma)
    {
        for(auto b : a) std::cout << b << '\t';
        std::cout << std::endl;
    }
}

/*try it with your file and see what happens, but remember: C++ 2011!*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <sstream>
#include <string>

int main()
{
    std::istringstream file // std::ifstream file( "teams.csv" ) ;
    (
         "id,name\n"
         "501,Abilene Chr\n"
         "502,Air Force\n"
         "503,Akron\n"
         "504,Alabama\n"
    );

    file.ignore( 10000, '\n' ) ; // throw away the first line

    int id ;
    char comma ;
    std::string name ;
    int line_number = 0 ;

    while( file >> id >> comma && std::getline( file, name ) )
    {
        std::cout << ++line_number << ". id: " << id << "  name: " << name << '\n' ;
    }
}

http://coliru.stacked-crooked.com/a/359275d4be852bc7
Topic archived. No new replies allowed.