473,791 Members | 2,947 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Very quick C++ I/O n00b question

Right now, I am reading a file line by line using getline() using this
code:

// Read file line by line, store the first 3 values on each line
in a vector and store the vector in a vector of vectors
while(getline(p eakReader, line)) {
istringstream lineStr(line);
vector<intpeak( 3);
if (!(lineStr >peak[0] >peak[1] >peak[2])) {
cerr << "Error reading peak file; will continue
without using peaks." << endl;
usePeaks = false;
break;
}
peaks.push_back (peak);
}
peakReader is an ifstream, line is a string.

I was wondering if there is an easy way to prevent this code from
reading the last line of the file without affecting any of the other
lines. The only way I can see doing it is by opening another input
file stream, iterating line-by-line through the file to tally the
number of lines in the file, and then check for the last line by its
line number, but I feel this is a rather lame way of doing it and
there has to be something better that can be accomplished in this one
loop. Thanks in advance for your help.

Aug 30 '07 #1
5 1471
<ch************ @gmail.comwrote in message
news:11******** **************@ q3g2000prf.goog legroups.com...
Right now, I am reading a file line by line using getline() using this
code:

// Read file line by line, store the first 3 values on each line
in a vector and store the vector in a vector of vectors
while(getline(p eakReader, line)) {
istringstream lineStr(line);
vector<intpeak( 3);
if (!(lineStr >peak[0] >peak[1] >peak[2])) {
cerr << "Error reading peak file; will continue
without using peaks." << endl;
usePeaks = false;
break;
}
peaks.push_back (peak);
}
peakReader is an ifstream, line is a string.

I was wondering if there is an easy way to prevent this code from
reading the last line of the file without affecting any of the other
lines. The only way I can see doing it is by opening another input
file stream, iterating line-by-line through the file to tally the
number of lines in the file, and then check for the last line by its
line number, but I feel this is a rather lame way of doing it and
there has to be something better that can be accomplished in this one
loop. Thanks in advance for your help.
One way to handle that problem is not to store the current line each time,
but store the previous line. I.E. in pseudo code

std::string LastLine;
std::string Line;
if ( std::getline(pe akReader, LastLine )
while ( std::getline( peakReader, Line )
{
// formatting here for LastLine into peak
peaks.push_back ( peak );
LastLine = ThisLine;
}

There is probalby another way, but something like this is what I'd probably
use.
Aug 31 '07 #2
On 2007-08-31 00:21, ch************@ gmail.com wrote:
Right now, I am reading a file line by line using getline() using this
code:

// Read file line by line, store the first 3 values on each line
in a vector and store the vector in a vector of vectors
while(getline(p eakReader, line)) {
istringstream lineStr(line);
vector<intpeak( 3);
if (!(lineStr >peak[0] >peak[1] >peak[2])) {
cerr << "Error reading peak file; will continue
without using peaks." << endl;
usePeaks = false;
break;
}
peaks.push_back (peak);
}
peakReader is an ifstream, line is a string.

I was wondering if there is an easy way to prevent this code from
reading the last line of the file without affecting any of the other
lines. The only way I can see doing it is by opening another input
file stream, iterating line-by-line through the file to tally the
number of lines in the file, and then check for the last line by its
line number, but I feel this is a rather lame way of doing it and
there has to be something better that can be accomplished in this one
loop. Thanks in advance for your help.
I was going to suggest the same solution as Jim Langstrom, so I'll just
make an observation instead. If you are always going to read read three
values from each line, using a vector to store them will be a bit
wasteful (unless you'll add more elements later). Instead use a structt:

struct MyValues {
int v1, v2, v3;
};

std::vector<MyV aluespeaks;

.....

MyValues val;
if (!(lineStr >val.v1 >val.v2 >val.v3 )) {

.....

--
Erik Wikström
Aug 31 '07 #3

<ch************ @gmail.comwrote in message...
Right now, I am reading a file line by line using getline() using this
code:

// Read file line by line, store the first 3 values on each line
in a vector and store the vector in a vector of vectors
while(getline(p eakReader, line)) {
istringstream lineStr(line);
vector<intpeak( 3);
if (!(lineStr >peak[0] >peak[1] >peak[2])) {
cerr << "Error reading peak file; will continue
without using peaks." << endl;
usePeaks = false;
break;
}
peaks.push_back (peak);
}
peakReader is an ifstream, line is a string.

I was wondering if there is an easy way to prevent this code from
reading the last line of the file without affecting any of the other
lines. The only way I can see doing it is by opening another input
file stream, iterating line-by-line through the file to tally the
number of lines in the file, and then check for the last line by its
line number, but I feel this is a rather lame way of doing it and
there has to be something better that can be accomplished in this one
loop. Thanks in advance for your help.
[ in case you don't want to use Jim's suggestion for some reason.]
Put a unique character in the first position of the last line, and test for
it.
Since you are reading in numbers, use something that is not a number.

// - in file -
$ this is the last line.
// ------

while( peakReader.peek () != '$' && getline(peakRea der, line) ){
// ....
} // while()

The 'peek()' will read a char without moveing the 'get pointer' in the file.
The 'while()' above will depend on 'getline()' leaveing the 'get pointer' at
the start of the next line ( so, don't do anything like a 'seekg() that
would move the pointer.)

or something like:

while( std::isdigit( peakReader.peek () ) && ....){....} // <cctype>

.... might work, depends on what the file contains (format).

Just some ideas, not tested.
--
Bob R
POVrookie
Aug 31 '07 #4
Hi!
[ in case you don't want to use Jim's suggestion for some reason.]
Put a unique character in the first position of the last line, and test for
it.
Since you are reading in numbers, use something that is not a number.
If he was to generate the file in the first place he could as well just
put the line at the beginning of the file :)

Frank
Aug 31 '07 #5
In article <11************ **********@q3g2 000prf.googlegr oups.com>,
ch************@ gmail.com says...

[ ... ]
I was wondering if there is an easy way to prevent this code from
reading the last line of the file without affecting any of the other
lines.
The easiest way is probably to read the last line, but not process it,
something like this:

// warning: untested code
std::string prev_line, curr_line;

std::getline(pe akReader, prev_line);

while (getline(peakRe ader, curr_line) {
peaks.push_back (process(prev_l ine));
prev_line = curr_line;
}

--
Later,
Jerry.

The universe is a figment of its own imagination.
Sep 1 '07 #6

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

Similar topics

1
1788
by: Matt | last post by:
I'd like to overwrite just one line of a binary file, based on a position set by seek(). Is there no way to do this? As far as I can tell I need to read the whole file, change the line, and write it all back out. Not exactly easy on the memory, but I see no other solution. so far: patchme.seek(offset) patchme.write(a2b_hex(edit)) # the data is in hex first patchme.close
3
1533
by: Anupam Kapoor | last post by:
hi all, a python n00b, so please bear with me. i have a simple question: i generally name python sources as a-simple-python-example.py. when i try to import a module named as above, i (obviously) get tracebacks from python interpreter. is there a way to continue naming python sources as above, and still use it as python modules ? i can ofcourse change the name to
33
1805
by: earthlinkmail | last post by:
....you experienced programmers of C; did you start with C? What course of study did you pursue to get to where you are today? Would you suggest starting with REALbasic first for a n00b? I am completely new to programming and using a Mac and would like some input as to where to begin a career in programming. I know this is probably a somewhat undefined question, but would appreciate you input/advice. Thanks.
1
1544
by: newgenre | last post by:
I am using a pre-built package of code for my site, which is called EasyDisc. All it does is it creates an interactive forum on your site, like any forum you see anywhere. I am having a problem getting started as I am new to .NET and sql. The app, once unzipped, tells me to "Make note of your SQL server name, username, password, database name. You need to supply these info. later." My problem is I don't know where to find out that info....
4
10146
by: onefry | last post by:
Hey I have this prog that i'm working on, starting my first c++ class and kind of a n00b to programming here it is #include <iostream> #include <cstdlib> using namespace std;
6
1506
by: Charles | last post by:
I am learning from the Accelerated C++ book. The following example doesn't work and I don't know why: #include <iostream> #include <string> int main () { const std::string exclam = "!"; const std::string message = "Hello" + ", world" + exclam; return 0; }
3
1328
by: rtlshred | last post by:
Hello I have just, just started C++ programing. the complier I am using is Dev C++ Here is my question: Once I have written some code, How do I run the program and see the output?
112
4762
by: Prisoner at War | last post by:
Friends, your opinions and advice, please: I have a very simple JavaScript image-swap which works on my end but when uploaded to my host at http://buildit.sitesell.com/sunnyside.html does not work. To rule out all possible factors, I made up a dummy page for an index.html to upload, along the lines of <html><head><title></title></ head><body></body></html>.; the image-swap itself is your basic <img src="blah.png"...
2
4230
by: benwah1983 | last post by:
Greetings, Here is my problem: The following code shows a div with two small nested divs (images with a title), then the div is closed. Another one opens and a "random text" is displayed. <div style="width: 500px;"> <div style="float: left; padding: 20px;"> Image Title 1<br/> <img src="test.jpg"/> </div> <div style="float: left; padding: 20px;">
4
1269
by: ig | last post by:
First off, I'm a python n00b, so feel free to comment on anything if I'm doing it "the wrong way." I'm building a discrete event simulation tool. I wanted to use coroutines. However, I want to know if there's any way to hide a yield statement. I have a class that I'd like to look like this: class Pinger(Actor): def go(self): success = True
0
9666
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9512
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10419
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10147
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9987
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7531
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6770
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5552
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2910
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.