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 :).

Recommended Answers

All 9 Replies

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

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&)'

You failed to include <string> header file.

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

Post the entire program, not just little pieces.

/* 
 * 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

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

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.

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.

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.