Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Opening a file and reading in lines of integers

Status
Not open for further replies.

tcat72

Technical User
Oct 3, 2001
4
0
0
US
I am trying to read in a line of integers. The file is like this:

4
3
0 0 1 0
0 1
2 3
3 4
4 0

the first two #s are fine, but lines 3-7 are giving me problems. How can I read each # in line 3 individually and perform some stuff on it, then continue to read the rest of the numbers and doing some stuff to them as well until I reach the end of the line? How can I do the same thing to the remaining lines?
 
ifstream infile("input.txt")

int next_digit;

while(!infile.eof() && infile.peek() != EOF)
{
infile>>next_digit;

... do stuff with next_digit
}

Matt
 
Well, if you want to do something special with each line of numbers and not associate it with the other numbers on the different line, then do this:

// stream from a file
ifstream fin("input.txt");
// store the entire line in a string
string line;
// store the number
int number;

// grabs one line of the file
while(getline(fin, line))
{
// so you will be able to take care one line at a time
// until it reaches the end of the line
istringstream temp(line);

// stream from the line and put the number in
temp >> number;

// ... do stuff with the number
} -Feryl
--> Just a silly software engineer wannabee.
If you feel a post has been helpful to you, click on the link at the bottom of their post to cast a vote for "TipMaster Of The Week". You don't need to be the one who asked the question to vote.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top