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

Edited by Nick Evan: Added code-tags

2
Contributors
9
Replies
10
Views
7 Years
Discussion Span
Last Post by Ancient Dragon
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

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

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

Edited by Kennych: n/a

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.

Edited by Kennych: n/a

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.

This article has been dead for over six months. Start a new discussion instead.
Be sure to adhere to our posting rules.