reading from .txt file
Nov 16, 2011 at 6:00pm UTC
Hello everyone, i'm still learning C++ and having trouble reading text files and putting them into strings.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string txt;
ifstream file("text.txt" );
if (file.is_open())
while (file.good())
getline(file, txt);
file.close();
cout << txt << endl;
system ("pause" );
return 0;
}
if i have a txt file that contains
it would come out
but if i have a txt file that contains
it would come out
how do i go about reading the entire txt file and displaying it the same way it is read from the txt file?
Nov 16, 2011 at 6:04pm UTC
The fastest solution would be to put the cout command inside of the while loop that starts at Line 11. Right now "getline(...)" is over writting 'Hello' with 'World' because you told it to.
Nov 16, 2011 at 6:06pm UTC
If you just want to display the text file, then print every line you read:
1 2 3 4 5 6
if (file.is_open())
while (file.good())
{
getline(file, txt);
cout <<txt<<endl;
}
Nov 16, 2011 at 6:51pm UTC
Your program reads all the lines.
But in every iteration in the while loop,
the older value of 'txt' gets overwritten with the next line.
So your program simply prints the last line.
Nov 16, 2011 at 7:02pm UTC
what i actually wanted to do was read a file that would take several lines of information
(name, age, sex, studentID)
above 2 files sent from 2 different students
and then output a file that looks like
1114007 Bob 20 M
1123150 Susan 22 F
this file is given to the instructor
how do i read each line and assign them into a string array?
Nov 17, 2011 at 5:37am UTC
I have found what i was looking for, thanks everyone for the input :)
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 <fstream>
#include <string>
using namespace std;
int main ()
{
string txt[10];
string line;
int i=0;
ifstream file ("example.txt" );
if (file.is_open()){
while (!file.eof()){
getline(file,line);
txt[i]=line;
i++;
}
}
file.close();
for (int j=0; txt[j]!="\0" ; j++)
cout << txt[j] << endl;
system("pause" );
return 0;
}
Topic archived. No new replies allowed.