Saturday, May 22, 2010

Need urgent help with I/O streams C++?

I have been able to solve the heap sort problem. The problem i have now is how to input from a file into a string. Its not as easy as it sound. it begins wiht a letter e.g. 'I' that means insert, 'S' for search, 'R' for remove or delete, 'C' for change and 'P' for print, all on multiple lines.


An example of an input will be:


I 2 34 56 78


P


S 2 30


R 56


P


I 45 67 43 23 45


C 45

Need urgent help with I/O streams C++?
#include %26lt;fstream%26gt;





read line by line


for each line, check the first char for the operation to perform, then parse the rest of the line and perform the operations... repeat until EOF





----UPDATES--------


if (myfile.is_open()){


fstream fileoperative("out2.txt",ios::out);


ifstream myfile("data.txt");


char buf[1024];


myfile.getline(%26amp;buf[0], 1024)





1. Why are you opening a file called out2.txt if you're trying to read an input file? Shouldn't it be called input2.txt or something? Also, for input you will want ios::in





You are using getline wrong. You are saying, take the first element of the buf buffer and store 1024 bytes into it. Just do


myfile.getline(buf, 1024)


Which will read 1024 bytes into buf. Then you can do buf[0] to get the first character





(ie. if ( buf[0] == 'P' || buf[0] == 'p' ) { ... }





------- MORE UPDATES--------


I think you are just confused about parsing.


See you only do one myfile.getline( buf, 1024 ) call


Get line will return after it has encountered a new line OR it has read 1024 characters (something to that effect it may only be 1023 but i dont recall off hand)





So now you have the entire line stored in buf


You first want to determine what operation you're going to be doing (as I described in the last update) and then you need to store the items you read into an array. Parsing is often done with the function strtok():





int values[ 50 ] ; // assume no more than 50 per line





int i = 0 ;





// offset by 2 to skip the command and space


char* textValue = strtok( buf+2, " " ) ;





while ( textValue != NULL ) {


values[ i++ ] = atoi( textValue ) ;


textValue = strtok( NULL, " " ) ;


}





// at this point your values should be stored in the array





// execute the command you read previously





// repeat the above for the remaining lines


No comments:

Post a Comment