1.11M Members

How to read lines in C++ from file.

 
0
 

Example of what im trying to do:

Definition: test.txt

Apples //line1
Coke //line2
Money/line3

#include <fstream>
using namespace std;
fstream teststream;
teststream.open("test.txt");
string line1;
string line2;
string line3;

//I want it so line1 = apples
//I wan tit so line2 = coke
//I want it so line3 = money

I'm not sure how to do this, so any help would be very appreciated :).

 
0
 

1) use ifstream, not fstream, to read a file. ifstream is easier to use.

2) use getline() to read an entire line that may or may not contain spaces.

ifstream in("test.txt);
getline(line1, in);
// do the same for the other lines
 
0
 

1) use ifstream, not fstream, to read a file. ifstream is easier to use.

2) use getline() to read an entire line that may or may not contain spaces.

ifstream in("test.txt);
getline(line1, in);
// do the same for the other lines

I tried this, but got the error main.cpp:42: error: no matching function for call to `getline(std::string&, std::ifstream&)'

 
0
 

You failed to include <string> header file.

 
0
 

I included
#include <iostream>
#include <string>
#include <fstream>

 
0
 

Post the entire program, not just little pieces.

 
0
 
/* 
 * File:   main.cpp
 * Author: Kunaal
 *
 * Created on November 25, 2009, 10:18 PM
 */

#include <stdlib.h>
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main(int argc, char** argv) {
string line1 = "";
string line2 = "";
string line3 = "";
ifstream in("test.txt");
getline(line1,in);

    return (EXIT_SUCCESS);
}

Text File:

apples
coke
money

 
0
 

My error, I had the parameters backwards. This will fix it getline(in, line1);

 
0
 

Thanks it works, but for some reason when I print line1 it flashes the first line really quickly then goes blank. I can access if i print out the indexes of line1, but i'm just curious why it does the above.

 
0
 

What compiler do you use? The problem most likely is caused by not adding something at the end of the program that makes it wait for keyboard input so that you can see what's on the screen. Add cin.get(); just before the return statement.

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: