473,395 Members | 1,885 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,395 software developers and data experts.

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(in, line)){
textlines.push(reinterpret_cast<void*>(&line));
}
works ok but the following is not printing out the lines

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

Aug 28 '05 #1
6 1710
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(in, line)){
textlines.push(reinterpret_cast<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<double*>(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.txt" );
double value;
while ( in_file >> value ) {
double_stack.push( value );
}
}
{
// print
while ( ! double_stack.empty() ) {
std::cout << double_stack.top() << '\n';
double_stack.pop();
}
}
}
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(in, line)){
Now you go through the file, overwriting the string contents with the
current line each time.
textlines.push(reinterpret_cast<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<double*>(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::initialize(void* dat, Link* nxt) {
data = dat;
next = nxt;
}

void Stack::initialize() { head = 0; }

void Stack::push(void* 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.cpp*************************
// 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(argc, 1); // File name is argument
ifstream in(argv[1]);
assure(in, argv[1]);
Stack textlines;
textlines.initialize();
string line;
// Read file and store lines in the Stack:
while(getline(in, line))
textlines.push(new string(line));
// Pop the lines from the Stack and print them:
string* s;
while((s = (string*)textlines.pop()) != 0) {
cout << *s << endl;
delete s;
}
textlines.cleanup();
} ///:~

//: :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 = "Requirement 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::ifstream& 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::ofstream& 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(argc, 1); // File name is argument
ifstream in(argv[1]);
assure(in, argv[1]);
Stack textlines;
textlines.initialize();
string line;
// Read file and store lines in the Stack:
while(getline(in, 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*)textlines.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******@gascad.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(argc, 1); // File name is argument
ifstream in(argv[1]);
assure(in, argv[1]);
Stack textlines;
textlines.initialize();
string line;
// Read file and store lines in the Stack:
while(getline(in, 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(in, line)){
textlines.push(new double( atof(line.c_str()) ));
}

// Pop the lines from the Stack and print them:
string* s;
while((s = (string*)textlines.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(in, 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
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...
7
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...
11
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...
4
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...
0
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...
2
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...
3
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...
6
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...
8
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...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
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,...
0
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...
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...
0
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...
0
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...

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.