Monday, May 24, 2010

C++ Programing Help!, usinng 'string' function to create 'ofstream' file name!?

im doing a program for my class. i have to make a 'string' function that takes the name of the ifstream file (data1.txt) and the string function changes that string into 'data1.csv'.





that way, when i go to open my ofstream file (which doesnt exist, so it'll create it), i use the call of the string function so it creates the file 'data1.csv'


....


here is what my function looks like...


string newoutput (string filename)


{


string newfilename;


int p;


filename.find('.');


p=filename.find('.');


cout %26lt;%26lt; filename.substr(0,p) %26lt;%26lt; ".csv";


return newfilename;


}





...then when i go to open the ofstream file, i have it saying...





result.open (newfilename);





....





but it does not compile. i think it has something to do with the way my function is set up. idk if its outputing it right or not. if i change "result.open (newfilename);" to "result.open ("data1.csv");" then it works exactly how it want it to. but my teacher wants me to use the string function. can anyone help me?

C++ Programing Help!, usinng 'string' function to create 'ofstream' file name!?
Your function actually returns the empty string because note that you have not assinged anything to "newfilename" within that function. Also, have you declared "newfilename" before you used it in the following line of code:





result.open (newfilename);





Note that you need to declare "newfilename" before you use it in the previous line (declaring it within the function is not enough because its scope is going to be within that function only).





I have rewritten your code and here is what I have:





string newoutput (string filename)


{


string newfilename;


int p = 0;





p = filename.find('.');


newfilename = filename.substr(0,p) + ".csv";


return newfilename;


}





string filename = "data1.txt";


string newfilename = newoutput(filename);


result.open(newfilename);


No comments:

Post a Comment