Friday, July 31, 2009

How do i use a string variable with input file handle in c++ ?

usually what i do is:





ifstream InputFile;


InputFile.open("sample.txt");





but instead of using a file name i want to use a string variable. This is what I have tried:





stream x = "sample.txt";


ifstream InputFile;


InputFile.open(x);





but it is not working ? anybody got suggestions ??

How do i use a string variable with input file handle in c++ ?
you want to use a string type, not stream. check documentation on the C++ STL libraries.





string input = //whatever is from the user


ifstream infile;


infile.open( input.c_str() );





...





"c_str()" just returns a char* buffer to methods that need it.
Reply:ok so what you need to do is declare a char array of string not a stream varaible








stream x ="blah blah" // wrong








char * x;





x = new char[10]; // or however long your characters are





// then





x = "text.txt"





ifstream InputFile;


InputFile.open(x);





// this should work also remeber to pick the iso mode for it good luck


No comments:

Post a Comment