473,387 Members | 1,575 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Help fixing file input reading routine?

Hi - I'm just learning basic file i/o stuff, and the following input
routine skips the first entry in text files. I would guess it's a
similar phenomenon as when there's a CR left in the buffer and you need
to do a cin.get() to clear it. But I really don't know. Lil help?

Another thing: I initially wanted to use the conditional-? operator
inline in the cout statement at the end. Doing so never worked
(compiles fine, just gives incorrect answers). Why is this?

The test file I used contained only "1 2 3 4 5 6 7 8 9 10" (without
quotes). Runs always left the 1 out of the loop value cout.

TIA!

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

const int SIZE = 60;
const int FILESIZEMAX = 1000;

int main()
{
char filename[SIZE];
ifstream inFile;

cout << "File name: ";
cin.getline(filename,SIZE);

inFile.open(filename);

if (!inFile.is_open())
{
cout << "Couldn't open " << filename << endl;
cout << "Terminating execution\n";
exit(EXIT_FAILURE);
}

double value;
double sum = 0.0;
int count = 0;
double avg = 0.0;

inFile >> value;

while (inFile.good() && count<FILESIZEMAX)
{
++count;
sum += value;
inFile >> value;
cout << value << endl;
}

if (inFile.eof())
{
cout << "End of file reached\n";
}
else if (inFile.fail())
{
cout << "Data mismatch.\n";
}
else
{
cout << "Input terminated for unknown reason.\n";
}

cout << "Items read: " << count << endl;
cout << "Sum: " << sum << endl;

avg = count !=0 ? sum/count: 0.0;

cout << "Average: " << avg << endl;
cout << endl;

inFile.close();

return 0;

Apr 13 '06 #1
4 1561
sh*************@gmail.com wrote:
Hi - I'm just learning basic file i/o stuff, and the following input
routine skips the first entry in text files. I would guess it's a
similar phenomenon as when there's a CR left in the buffer and you need
to do a cin.get() to clear it. But I really don't know. Lil help?

Another thing: I initially wanted to use the conditional-? operator
inline in the cout statement at the end. Doing so never worked
(compiles fine, just gives incorrect answers). Why is this?

The test file I used contained only "1 2 3 4 5 6 7 8 9 10" (without
quotes). Runs always left the 1 out of the loop value cout.
[snip]
int main()
{
char filename[SIZE];
ifstream inFile;

cout << "File name: ";
cin.getline(filename,SIZE);

inFile.open(filename);

if (!inFile.is_open())
{
cout << "Couldn't open " << filename << endl;
cout << "Terminating execution\n";
exit(EXIT_FAILURE);
}

double value;
double sum = 0.0;
int count = 0;
double avg = 0.0;

inFile >> value;
Here, you read in the first value from the file.
while (inFile.good() && count<FILESIZEMAX)
{
++count;
sum += value;
inFile >> value;
Here, you read in the second, third, fourth, etc. values from the file.
The first value you read in above is now gone.
cout << value << endl;
}
Better would be to do the reading in the loop condition:

while ((count < FILESIZEMAX) && (inFile >> value))
{
// ...
}
avg = count !=0 ? sum/count: 0.0;

cout << "Average: " << avg << endl;


Try:

cout << "Average: " << ((count != 0) ? sum / count : 0.0) << endl;

I find that using the ternary operator (x ? y : z) directly in output
statements requires extra sets of parentheses, probably due to the
relative precedence of the "<<" and the "?:" operators.

--
Marcus Kwok
Replace 'invalid' with 'net' to reply
Apr 13 '06 #2
>I find that using the ternary operator (x ? y : z) directly in output
statements requires extra sets of parentheses, probably due to the
relative precedence of the "<<" and the "?:" operators.
Thanks! Worked like a charm!
while ((count < FILESIZEMAX) && (inFile >> value))


Question about the loop-reading-variable-assigment combo though. I
assume the stream assignment in the while condition is cast as a
boolean or something similar? does the cast-assignment have exactly the
same truth conditions as my original inFile.good condition? If you
don't have a quick and snappy answer, that's cool - I can go look that
up somewhere...

Thanks for the tips!

Apr 13 '06 #3
Please do not erase the attribution lines, so that people can see who
wrote what. I have added it back in.

sh*************@gmail.com wrote:
Marcus Kwok wrote:
while ((count < FILESIZEMAX) && (inFile >> value))
Question about the loop-reading-variable-assigment combo though. I
assume the stream assignment in the while condition is cast as a
boolean or something similar?


Almost, see:
http://www.parashift.com/c++-faq-lit....html#faq-15.4
does the cast-assignment have exactly the
same truth conditions as my original inFile.good condition? If you
don't have a quick and snappy answer, that's cool - I can go look that
up somewhere...


I'm not certain if it's *exactly* the same, but in pretty much all cases
it should do what you want. As far as I have seen, it is a "correct"
idiomatic C++ way of reading input though.

--
Marcus Kwok
Replace 'invalid' with 'net' to reply
Apr 13 '06 #4
>> Question about the loop-reading-variable-assigment combo though. I
assume the stream assignment in the while condition is cast as a
boolean or something similar?
Almost, see:
http://www.parashift.com/c++-faq-lit....html#faq-15.4


Ah. Sort of a compromise between casting as boolean and allowing nested
cin stream reads. Coolness. Thanks!

Apr 13 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: DJP | last post by:
Hi, I need to read a file programmatically until end of file. My logic is as follows: while(!feof(Fp)) { fgets(readLine,10000,Fp);
28
by: Colin JN Breame | last post by:
Hi, Fairly new to C. What is the best way to read a line (\n terminated) from a file? Ive looked at fscanf but was not sure which format specifier to use. (%s perhaps). Thanks Colin
1
by: Magix | last post by:
Hi, I have these string data: str_data1, str_data2, str_data3, which capture some value after a routine process A. Then I would like to write (append) these 3 string values into a text file each...
6
by: James Radke | last post by:
Hello, I have a multithreaded windows NT service application (vb.net 2003) that I am working on (my first one), which reads a message queue and creates multiple threads to perform the processing...
2
by: DraguVaso | last post by:
Hi, I need a FAST way to put the content of a file in a datatable (one record for each line in the file). I have a routine for it, but it takes me too much time (2-5 seconds for each file) to...
5
by: leorulez | last post by:
Hi all I need to read the number of non-empty lines in a text file char c; int i=0,j=0; while( !feof( fp1 ) ) { fgets( c , 100 , fp1);
9
by: =?Utf-8?B?QnJpYW4gQ29vaw==?= | last post by:
I want to open a text file and format it into a specific line and then apply color to a specific location of the text and then display it in a RichTextBox after all of this is done. I can do all...
1
by: dwaterpolo | last post by:
Hi Everyone, I am trying to read two text files swY40p10t3ctw45.col.txt and solution.txt and compare them, the first text file has a bunch of values listed like: y y y y y y y
0
by: SOI_0152 | last post by:
Hi all! Happy New Year 2008. Il hope it will bring you love and happyness I'm new on this forum. I wrote a stored procedure on mainframe using DB2 7.1.1 and IBM language c. Everything works...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.