Reading from a file works the same way as reading from any other istream, such as cin:
//read up to newline
std::string str;
std::getline(cin, str);
//read up to whitespace (after a word or character)
std::string str;
cin >> str;
With files, replacecin with the name of your ifstream
and just repeat that three times.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
I just want to ask how to reach the position which I want
Just repeat the code Bench posted until you get to the desired line. You will have to use a loop and a counter integer to keep track of the line number that was just read. If you are confused about loops -- which is understandable -- you should read about them in your text book.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
but how to use pointer to move the reading postion? point to what?
Looks like you need some code right? Otherwise you're just going to be going around in circles?
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
is he/she looking for the 3rd word or line?
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
How about this?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream read ( "c:\\yourfile.txt" );
string my_string;
int counter = 0;
while (getline(read, my_string, '\n'))
{
if (counter ==2 )
{
cout<<"hey you hit the third line " << my_string;
}
counter = counter + 1;
}
read.close();
cin.get();
}
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
Thank you to all of you! I made a mistake, missed the line "and just repeat that three times" which Bench posted, or I could understand it earlier.
Really!?!? Then maybe instead of wasting 6 hours, if you had just postedyour code, it could have been corrected in an hour.
WaltP
Posting Sage w/ dash of thyme
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944