Reputation:
Quick question,
Assuming that you were told to read input, only 10 lines, from a text file; nevertheless, the text file has 40 lines. Would it be bad programming to do the following:
while ( infile >> input && num_lines < 10 ) {
do whatever...
num_lines++;
}
// closed file
infile.close();
Is there a better way to do this??
I should have mentioned that when i said "lines" i merely meant the following:
planet
tomorrow
car
etc
So yes, to read a line of text, get line function should be implemented
Upvotes: 1
Views: 6157
Reputation: 206567
infile >> input
is not the right method to read a line of input. It stops reading when a whitespace character is encountered in a line. You should to use std::getline(infile,input)
.
while ( std::getline(infile, input) && num_lines < 10 ) {
do whatever...
num_lines++;
}
Upvotes: 2
Reputation: 66194
It wouldn't be bad programing. That you're checking your input success is better than most people new to this, so don't feel bad about it. Your current loop, however, would not be correct.
Things wrong:
Try this:
int num_lines = 0;
std::string input;
for (; num_lines < 10 && std::getline(input); ++num_lines)
{
// do-whatever
}
// num_lines holds the number of lines actually read
Edit: Updated after question changed.
The input file you have are words. If you want to ensure you receive only a single word off each line, and they must be line-separated, more work is involved:
#include <iostream>
#include <sstream>
int num_lines = 0;
std::string input;
while (num_lines < 10 && std::getline(input))
{
std::istringstream iss(input);
std::string word;
if (iss >> word)
{
// do-whatever with your single word.
// we got a word, so this counts as a valid line.
++num_lines;
}
}
This will skip blank lines and only process the single word at the beginning of each line that has content. It could further be enhanced to ensure the word read was the only content on the line aside from whitespace and the newline or EOF, but I seriously doubt you need error checking that tight (or even this tight).
Example Input
one
two
three four
five
six
seven
eight
nine
ten
eleven twelve
Processed Words
one
two
three
five
six
seven
eight
nine
ten
eleven
Both four
and twelve
are ignored, likewise the blank line between five
and six
. Whether this is what you seek is your call, but at least you have something closer than before.
Upvotes: 3