473,854 Members | 1,581 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

program error

Hello

I wrote a code which is suppose to read a file which contains lines of
double and prints it out.

thanks for helping

double.txt***** *************** *************** ****
1.01
2.0301
3.0604
4.10101
5.15202

in a stack.h I have
//stack.h******** *************** *************** **
#ifndef STACK_H
#define STACK_H

struct Stack
{
struct Link
{
void* data;
Link* next;
void initialize (void* dat, Link* nxt);
}
* head;
void initialize ();
void push (void* dat);
void* peek ();
void* pop ();
void cleanup ();
};
#endif

in my main.cpp
string line;
while(getline(i n, line)){
textlines.push( reinterpret_cas t<void*>(&line) );
}
works ok but the following is not printing out the lines

double* s;
while(( s = static_cast<dou ble*>(textlines .pop() )) != 0) {
cout << *s << endl;
delete s;
}
LocalWords: txt ifndef struct endif cpp ok

Aug 28 '05 #1
6 1746
Baloff wrote:
Hello

I wrote a code which is suppose to read a file which contains lines of
double and prints it out.
[snip] in a stack.h I have
//stack.h******** *************** *************** **
#ifndef STACK_H
#define STACK_H

struct Stack
{
struct Link
{
void* data;
Link* next;
void initialize (void* dat, Link* nxt);
}
* head;
void initialize ();
void push (void* dat);
void* peek ();
void* pop ();
void cleanup ();
};
#endif
Hm, you are using a stack, so maybe you want to revert the order in
printing?

All these void pointers are bad. You should use std::stack.

in my main.cpp
string line;
while(getline(i n, line)){
textlines.push( reinterpret_cas t<void*>(&line) );
}
works ok ...
Really? Now, I am pretty sure that this stores some *void items in your
stack, all of which will happily point to the address of the string
variable line which did not change!

... but the following is not printing out the lines

double* s;
while(( s = static_cast<dou ble*>(textlines .pop() )) != 0) {
which kind of magic is this cast supposed to perform? textlines.pop() will
return a *void pointing to &line. Now you are telling the compiler that it
should not expect a string there but treat the bytes there as the
representation of a double. [You might want to have a look into
boost::lexical_ cast!]
cout << *s << endl;
delete s;
Here, you are freeing memory that you nerver allocated!
}


Use the standard library:

#include <stack>
#include <iostream>
#include <string>
#include <fstream>

int main ( void ) {
std::stack< double > double_stack;
{
// read
std::ifstream in_file ( "numbers.tx t" );
double value;
while ( in_file >> value ) {
double_stack.pu sh( value );
}
}
{
// print
while ( ! double_stack.em pty() ) {
std::cout << double_stack.to p() << '\n';
double_stack.po p();
}
}
}
Best

Kai-Uwe Bux
Aug 28 '05 #2
Baloff wrote:
Hello

I wrote a code which is suppose to read a file which contains lines of
double and prints it out.

thanks for helping

double.txt***** *************** *************** ****
1.01
2.0301
3.0604
4.10101
5.15202

in a stack.h I have
//stack.h******** *************** *************** **
#ifndef STACK_H
#define STACK_H

struct Stack
{
struct Link
{
void* data;
Link* next;
void initialize (void* dat, Link* nxt);
}
* head;
void initialize ();
void push (void* dat);
void* peek ();
void* pop ();
void cleanup ();
};
#endif

in my main.cpp
string line;
You define one single string here.
while(getline(i n, line)){
Now you go through the file, overwriting the string contents with the
current line each time.
textlines.push( reinterpret_cas t<void*>(&line) );
Then you put a pointer to the string object into your stack. Note that it's
always the same string object and thus always the same pointer value. So at
the end, you have a stack of pointers that point all to the same string,
which contains the last line of your file, since that is what was last
written to it.
}
works ok but the following is not printing out the lines

double* s;
while(( s = static_cast<dou ble*>(textlines .pop() )) != 0) {
You cannot just take a pointer to a string and treat it as if it were a
pointer to double. This will not parse the string. It just interprets the
bits that the string is composed of as double value. The result is of
course garbage.
cout << *s << endl;
delete s;
}
LocalWords: txt ifndef struct endif cpp ok


Wha?

Aug 28 '05 #3
I think I need to show the whole code, it is an exercise form Thinking
In C++ by Bruce Eckel. page 255 (8)
I need to make the Stack example in the book holds doubles, fill it
with 25 double values and print them out.

thanks

//: C04:Stack.h**** *************** ***********
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Nested struct in linked list
#ifndef STACK_H
#define STACK_H

struct Stack {
struct Link {
void* data;
Link* next;
void initialize(void * dat, Link* nxt);
}* head;
void initialize();
void push(void* dat);
void* peek();
void* pop();
void cleanup();
};
#endif // STACK_H ///:~

//: C04:Stack.cpp {O}************ *************
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Linked list with nesting
#include "Stack.h"
#include "../require.h"
using namespace std;

void
Stack::Link::in itialize(void* dat, Link* nxt) {
data = dat;
next = nxt;
}

void Stack::initiali ze() { head = 0; }

void Stack::push(voi d* dat) {
Link* newLink = new Link;
newLink->initialize(dat , head);
head = newLink;
}

void* Stack::peek() {
require(head != 0, "Stack empty");
return head->data;
}

void* Stack::pop() {
if(head == 0) return 0;
void* result = head->data;
Link* oldHead = head;
head = head->next;
delete oldHead;
return result;
}

void Stack::cleanup( ) {
require(head == 0, "Stack not empty");
} ///:~

//: C04:StackTest.c pp************* ************
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
//{L} Stack
//{T} StackTest.cpp
// Test of nested linked list
#include "Stack.h"
#include "../require.h"
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main(int argc, char* argv[]) {
requireArgs(arg c, 1); // File name is argument
ifstream in(argv[1]);
assure(in, argv[1]);
Stack textlines;
textlines.initi alize();
string line;
// Read file and store lines in the Stack:
while(getline(i n, line))
textlines.push( new string(line));
// Pop the lines from the Stack and print them:
string* s;
while((s = (string*)textli nes.pop()) != 0) {
cout << *s << endl;
delete s;
}
textlines.clean up();
} ///:~

//: :require.h***** *************** **********
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Test for error conditions in programs
// Local "using namespace std" for old compilers
#ifndef REQUIRE_H
#define REQUIRE_H
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <string>

inline void require(bool requirement,
const std::string& msg = "Requiremen t failed"){
using namespace std;
if (!requirement) {
fputs(msg.c_str (), stderr);
fputs("\n", stderr);
exit(1);
}
}

inline void requireArgs(int argc, int args,
const std::string& msg =
"Must use %d arguments") {
using namespace std;
if (argc != args + 1) {
fprintf(stderr, msg.c_str(), args);
fputs("\n", stderr);
exit(1);
}
}

inline void requireMinArgs( int argc, int minArgs,
const std::string& msg =
"Must use at least %d arguments") {
using namespace std;
if(argc < minArgs + 1) {
fprintf(stderr, msg.c_str(), minArgs);
fputs("\n", stderr);
exit(1);
}
}

inline void assure(std::ifs tream& in,
const std::string& filename = "") {
using namespace std;
if(!in) {
fprintf(stderr, "Could not open file %s\n",
filename.c_str( ));
exit(1);
}
}

inline void assure(std::ofs tream& out,
const std::string& filename = "") {
using namespace std;
if(!out) {
fprintf(stderr, "Could not open file %s\n",
filename.c_str( ));
exit(1);
}
}
#endif // REQUIRE_H ///:~
LocalWords: Eckel txt struct ifndef dat endif namespace std nxt newLink cpp
LocalWords: oldHead StackTest fstream iostream int argc argv requireArgs
LocalWords: ifstream textlines getline cstdio cstdlib inline bool const msg
LocalWords: args requireMinArgs minArgs

Aug 28 '05 #4
Baloff wrote:

I think I need to show the whole code, it is an exercise form Thinking
In C++ by Bruce Eckel. page 255 (8)
I need to make the Stack example in the book holds doubles, fill it
with 25 double values and print them out.
So then why don't you do exactly that?
int main(int argc, char* argv[]) {
requireArgs(arg c, 1); // File name is argument
ifstream in(argv[1]);
assure(in, argv[1]);
Stack textlines;
textlines.initi alize();
string line;
// Read file and store lines in the Stack:
while(getline(i n, line))
textlines.push( new string(line));
You are not filling the stack with 'doubles'. You are
filling it with std::string's.

Either you *read* the file not with getline into a std::string
but eg. into a double or you *convert* the string (which
holds the textual representation of that number) into
an actual number.
// Pop the lines from the Stack and print them:
string* s;
while((s = (string*)textli nes.pop()) != 0) {


This will be wrong in any case. The stack holds pointers to
double, not to std::string!
--
Karl Heinz Buchegger
kb******@gascad .at
Aug 29 '05 #5
Karl Heinz Buchegger <kb******@gasca d.at> writes:
Baloff wrote:

I think I need to show the whole code, it is an exercise form Thinking
In C++ by Bruce Eckel. page 255 (8)
I need to make the Stack example in the book holds doubles, fill it
with 25 double values and print them out.
So then why don't you do exactly that?

to summarize the problem and reduce your time of reading a long post
at first.
int main(int argc, char* argv[]) {
requireArgs(arg c, 1); // File name is argument
ifstream in(argv[1]);
assure(in, argv[1]);
Stack textlines;
textlines.initi alize();
string line;
// Read file and store lines in the Stack:
while(getline(i n, line))
textlines.push( new string(line));
You are not filling the stack with 'doubles'. You are
filling it with std::string's.

Either you *read* the file not with getline into a std::string
but eg. into a double


how else would you read the file 'each line into a double'?
or you *convert* the string (which
holds the textual representation of that number) into
an actual number.


like this?
string line;
while(getline(i n, line)){
textlines.push( new double( atof(line.c_str ()) ));
}

// Pop the lines from the Stack and print them:
string* s;
while((s = (string*)textli nes.pop()) != 0) {


This will be wrong in any case. The stack holds pointers to
double, not to std::string!
--
Karl Heinz Buchegger
kb******@gascad .at

Aug 29 '05 #6
Baloff wrote:
Either you *read* the file not with getline into a std::string
but eg. into a double
how else would you read the file 'each line into a double'?


come on.

double value;

while( in >> value ) {
..
}

or you *convert* the string (which
holds the textual representation of that number) into
an actual number.


like this?
string line;
while(getline(i n, line)){
textlines.push( new double( atof(line.c_str ()) ));
}


Yep.
But atof() isn't a very good function. There is no way to check
if the string realy represents a valid number. Other methods
would be to eg. use string stream.
This topic has been beaten to death in this newsgroup. Search
the archives at google.

--
Karl Heinz Buchegger
kb******@gascad .at
Aug 30 '05 #7

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

Similar topics

2
14174
by: Mike | last post by:
I am sure that I am making a simple boneheaded mistake and I would appreciate your help in spotting in. I have just installed apache_2.0.53-win32-x86-no_ssl.exe php-5.0.3-Win32.zip Smarty-2.6.7.tar.gz on a system running WindowsXP SP2. Apache and PHP tested out fine. After adding Smarty, I ran the following http://localhost/testphp.php
7
18604
by: Dave | last post by:
I created a program using VB6 under WIN 98. The program uses an ado database. When I use the package and deployment program in VB6 on this program and then install it on a machine with XP Pro on it, I get the Provider can not be found error.. Any Ideas....I Hope
11
8531
by: anuradha.k.r | last post by:
hi, i am writing a socket program in python,both client side and server side.I've written the client side which is working perfectly fine(checked it against server program written in C).but as for my server program written in python it simply hangs.it does not show any error also.I've tried sample programs available .I don understand what the reason is as i am quite new to it. here is teh server side program: ///////////////////////
4
4021
by: muser | last post by:
Can anyone run this program through their compiler or if they can see a logical error please point it out. I have my tutor working on it at the moment but I would rather a less ambigious response than the one I think he will provide. The test data, A:\\"514650.txt", appears at the end of the program. The problem is that the program won't read this file and the debugger as far as i know how to work it won't point out the mistake of any....
0
6154
by: Tom Lee | last post by:
Hi, I'm new to .NET 2003 compiler. When I tried to compile my program using DEBUG mode, I got the following errors in the C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7 \include\xdebug file as folows. I need help to resolve them ASAP: cl /c /nologo /MDd /W3 /Od /GR /GM /Zi /GX /D "_DEBUG" /D " WIN32" /D "_W INDOWS" /D "_WINDLL" /D "_AFXDLL" /D "_MBCS" /D "_USRDLL" /
2
7535
by: bbxrider | last post by:
for win2k adv server/iis5.0 trying to run an external program from my asp routine that has multiple parameters, see following set shell = server.createobject("wscript.shell") shell.Run """f:\phsData\htmldoc\htmldoc.exe"" --webpage -f phsnew.pdf phsnew.htm" program either doesn't get invoked, or has an error, but since it has no error log i can't check that,
3
5271
by: Mark Rockman | last post by:
------ Build started: Project: USDAver2, Configuration: Debug .NET ------ Preparing resources... Updating references... Performing main compilation... error CS0583: Internal Compiler Error (0xc0000005 at address 535F072A): likely culprit is 'BIND'. An internal error has occurred in the compiler. To work around this problem, try simplifying or changing the program near the locations listed below. Locations at the top of the list are...
6
3136
by: Ken | last post by:
When running a program in the debugger, what would cause it to crash without any error messages? I get "The program has exited with code 0 (0x0)". The program is a MDI app with threading for several serial ports. It only crashes when data is being received on one or more of the serial ports. Could someone please give me some ideas about what would cause a program to terminate in this way? Thanks....
8
3294
by: karthikbalaguru | last post by:
Hi, One of my python program needs tkinter to be installed to run successfully. I am using Redhat 9.0 and hence tried installing by copying the tkinter-2.2.2-36.i386.rpm alone from the CD 3 to my pc. But, it is not getting installed and is failing by throwing the below errors. Should i need to configure / install any specific files for resolving this issue ?
0
9901
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
9751
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
11025
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...
0
10682
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7915
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
7082
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
5743
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4562
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4159
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.