Error with I/O function

Pages: 12
> For example, the assignment specified "a" function to read, reverse and write the sequence.
nolyc wrote:
You're trying to do X, and you thought of solution Y. So you're asking about solution Y, without even mentioning X. The problem is, there might be a better solution, but we can't know that unless you describe what X is.

Last edited on
Sorry for the ambiguity I just don't want to make it like I'm forcing my whole homework requirements down people's throat.

Basically the assignment requires me to read three types: int, float and char.

So it'd look something like this,
In file
int 3 1 2 3
float 2 1.0 4.0


Out file result:
int 3 3 2 1
float 2 4.0 1.0


There's an unknown number of lines and three fields seen above.
Type, Size of seq, and then the sequence itself.

My job is to read a file like that, reverse the sequence and then write it in the file with the same format.

So far I've dumbed down my code to the most basic level possible. However, I'm still having trouble x[.

My ostringstream is not getting the characters and it's giving me random jargon.
e.g.
0x7ffdd5dc54a0


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*
 * reader.h
*/

#ifndef READER_H_
#define READER_H_

#include <fstream>
#include <sstream>
#include <iostream>
#include <string>

class Reader {
public:
	Reader();
	~Reader();
	void inverseWrite(std::ifstream&, std::ofstream&);
	void readData(std::ifstream&);
	void reverseData(std::string);
	void writeData(std::ofstream&);
	int readLine(std::ifstream&);


private:
	std::string dType;
	int dSize;
	std::string dSeq;
	//
	int *iPtr;
	float *floatPtr;
	char *charPtr;
	int numberOfLines;
	std::ostringstream fullText;
	std::ostringstream reversedOutput;
};

#endif /* READER_H_ */

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
 * main.cpp
 */ #include "reader.h"

int main(int argc, char *argv[]){
	std::cout << "Have " << argc << " arguments:" << std::endl;
	   for (int i = 0; i < argc; ++i) {
	       std::cout << argv[i] << "\n";
	   }

	std::ifstream inFile(argv[1]);
	if (!inFile)
		std::cout << "File not open";

	std::ofstream outFile(argv[2]);
	Reader obj;

	obj.inverseWrite(inFile, outFile);

	inFile.close();
	outFile.close();
}

My main code performs the test, nothing really important in there.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
 * reader.cpp
 */
#include "reader.h"

Reader::Reader():
	numberOfLines(0)
{}
Reader::~Reader(){
	delete iPtr;
	delete floatPtr;
	delete charPtr;
}
void Reader::inverseWrite(std::ifstream& read, std::ofstream& write){
	readLine(read);
	readData(read);
	writeData(write);
}
void Reader::readData(std::ifstream& read){
	while (read >> dType){
		read >> dSize;
		std::getline(read, dSeq);
		reverseData(dSeq);
		fullText << reversedOutput << "\n"; //HERE IS A PROBLEM
	}
} //Read data and set ostringstream
void Reader::reverseData(std::string seq){
	std::stringstream tempLine(seq);
	if (dType == "int"){
		int tempValue;
		iPtr = new int[dSize];
		for (int i=0 ; i < dSize; i++){
				tempLine >> tempValue;
				iPtr[i] = tempValue;
		}
		reversedOutput << dType << " " << dSize << " "; //HERE IS A PROBLEM TOO
		for (int i = dSize-1; i >=0; i--)
			reversedOutput <<  iPtr[i] << " ";
	}
	else if (dType == "float"){
		float tempValue;
		floatPtr = new float[dSize];
		for (int i=0 ; i < dSize; i++){
			tempLine >> tempValue;
			floatPtr[i] = tempValue;
		}
		reversedOutput << dType;
		for (int i = dSize-1; i >=0; i--)
			reversedOutput <<  floatPtr[i] << " ";
	}
	else if (dType == "char"){
		char tempValue;
		charPtr = new char[dSize];
		for (int i=0; i <dSize; i++){
			tempLine >> tempValue;
			charPtr[i] = tempValue;
		}
		reversedOutput << dType << " " << dSize << " ";
		for (int i= dSize-1; i>=0; i--)
			reversedOutput << charPtr[i] << " ";
	}
}

void Reader::writeData(std::ofstream& write){
	write << fullText;
}
int Reader::readLine(std::ifstream& read){
		numberOfLines = 0;
		std::string holder;
		while (std::getline(read,holder))
			numberOfLines++;
		read.clear();
		read.seekg(0);
		return numberOfLines;
}


My main problem here is my std::ostringstream reversedOutput
is not registering the input I'm giving.
For example:
reversedOutput << dType << " " << dSize << " ";
Would just give me an address of some sort like :
0x7ffdd5dc54a0


Sorry for the burden, I'm just having a really hard time mashing all the concept together with I/O streams
My whole code is a mess I've been working on this for days and it's just so hard to tackle all these bugs that I get.
Last edited on
¿is it necessary to read the integers into an int variable?
you may simply read "words" and then reverse them
1
2
3
4
5
6
std::string word;
std::vector<std::string> sentence;
while(line>>word)
   sentence.push_back(word);

std::reverse( sentence.begin(), sentence.end() );



If you are going to make a different process according to the type (by instance, reverse for float may be 1/f), you can do 3 functions and choose with the first word
1
2
3
4
5
input >> type;
if( type=="int")
   proccess_int(input);
else if( type=="float" )
   proccess_float(input);



> fullText << reversedOutput << "\n"; //HERE IS A PROBLEM
http://www.cplusplus.com/reference/sstream/stringstream/str/


About your dynamic allocation
new -> delete

new[] -> delete[]
don't mix them.

Also, note that you are allocating inside a loop, but deallocating only once, in the destructor. So you are only freeing the last allocation, and all the others leaked.
Last edited on
That's true the process functions would reduce the bulk in my code, but it's still a problem that my ostringstream isn't writing.

I didn't actually consider your option since I thought that string reads in spaces too. However looking at your code I didn't realize that the line >> operator would cut off at every white space.

I'll give it a try next morning It's 7AM here I'm sure it will work, It's both saddening and relieving to know that the solution was just this simple.

While the teacher was explaining the assignment she gives alternative options to do the assignment and said that using a Data class to store all sentences is the best method instead of just reversing right away and writing it.

It affected me to the point that I had a fixed linear view to tackle this assignment.


Alright I haven't gone to sleep because this assignment is keeping me up, I fixed the stringstream input as you pointed out ne555. The ostreamstring is still a problem though because when I do a basic assignment of
reversedOutput << dType << " " << dSize << " ";
then
std::cout << reversedOutput
I would get jargon.

When I run the program absolute nothing happens
This is all that happens
Have 2 arguments:
/home/jacky/Dropbox/eclipse-workspace/Assignment-4BASIC/Debug/Assignment-4BASIC
/home/jacky/Dropbox/eclipse-workspace/Assignment-4BASIC/src/testio.dat
Last edited on
Just wondering, if the methodology was to simply read strings, rather than assign to types - wouldn't that make the assignment rather trivial in terms of the level of the course? I mean the OP was all prepared to do templates & exceptions - not sure if that really is overkill, but I have a suspicion that it might not be. If the OP is aware of and able to do such things - then that tells me it's not an introductory course - maybe 2nd year University level at a guess, or first year second semester.

Sorry for the ambiguity I just don't want to make it like I'm forcing my whole homework requirements down people's throat.


On the contrary:

Perhaps if we could see the the text of the assignment question in full - then we can all be on the same page?
std::cout << reversedOutput.str()


> wouldn't that make the assignment rather trivial
.zo'o the lesson was KISS
@ne555

the lesson was KISS


Right-Oh, and you are very probably quite right :+) A betting person is way more likely to back you rather than me :+) !

Despite that, IMO it would be good (for me, at least) to see the actual question, to be sure, to be sure. At the moment we seem to have several interpretations, and possibly interpretation upon interpretation.

Also, I don't want to imply that I am doubting what you are saying - it's more for my own peace of mind.

In the end, it doesn't matter - I just like to have my own critical thinking (and some actual evidence to base it on), regardless of how right others might be, or how wrong I might finish up being. Either way, it's all about the learning :+)

Any way, Regards and thanks as per always for your expert insight.

Cheers
Alright if you insist TheIdeasMan I'll provide the description below on pastebin.com:
http://pastebin.com/bUAwbB22

I implemented ne555 version of ignoring the type and simply assigning the string to a vector. As much as I want to improve the assignment I really don't want to invest the time on it because I have other assignments on PHP that I haven't even started due in 24 hours DX

You are right the assignment specifies specifically checking the type. However, while talking to the teacher and mentioning exactly your point, she seemed to not really care about that topic and specified to just "focus on IO" as is.

I really want to thank you guys for investing all that time on this assignment. I really appreciate it!
Last edited on
Ok Thanks for that :+)

So I think it would be worthwhile in the future to post a link to the assignment, at the start of the Topic.

In hindsight, I wouldn't have said anything about vectors or unions. I guess that I tend to express my instincts about what to do - given the code that is posted. But that might not match up with the actual question, possibly because of the restrictions inherent in the assignment.

Any way, Best of Luck , I can see you put in a really good effort to your work (pulling all-nighters etc), so I think you deserve to do well, and I think you will overall.

It's also good that you are prepared to think for yourself and do problem solving - I came across so many that aren't and are just after a quick solution, and don't appreciate questions that do require them to think.

And it's a good feeling to discover that advice given by all the respondents is truly appreciated - even though the end result wasn't perhaps as good as it could have been.

So - Good Work

Regards <8+)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
#include <iterator>
#include <cctype>
#include <fstream>

template < typename T >
bool reverse_copy_items( std::istream& fin, std::ostream& fout, std::size_t n )
{
    fout << "count:" << n << "  " ;

    std::vector<T> seq(n) ; // "Each record 'can be' stored..." - can be, not 'must be'

    for( std::size_t i = 0 ; i < n ; ++i )
        if( !( fin >> seq[i] ) ) throw std::runtime_error( "badly formed input" );

    for( auto iter = seq.rbegin() ; iter != seq.rend() ; ++iter ) fout << *iter << ' ' ;

    return fin && fout << '\n' ;
}

bool reverse_copy( std::ifstream fin, std::ofstream fout )
{
    bool ok = true ;
    std::string type_tag ;

    std::size_t cnt ;
    while( ok && fin >> type_tag >> cnt )
    {
        for( char& c : type_tag ) c = std::tolower(c) ; ;

        if( type_tag == "int" ) ok = reverse_copy_items<int>( fin, fout << "int ", cnt ) ;
        else if( type_tag == "float" ) ok = reverse_copy_items<float>( fin, fout << "float ", cnt ) ;
        else if( type_tag == "char" ) ok = reverse_copy_items<char>( fin, fout << "char ", cnt ) ;

        else throw std::domain_error( "unsupported type" ) ;
    }

    // if( !ok ) throw ...
    return fin.eof() && fout ;
}

int main( int argc, char* argv[] )
{
    // validate coomand line arguments etc.
    // try ... etc.
    if( argc == 3 ) reverse_copy( std::ifstream( argv[1] ), std::ofstream( argv[2] ) ) ;
}
Topic archived. No new replies allowed.
Pages: 12