Opening a File for reading
Jun 29, 2012 at 3:06pm UTC
Is there any possible way to read the file name from a string variable? doing something like this:
1 2 3 4 5 6 7 8 9 10 11 12
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
string str= "C:\CPP\try" ;
ifstream in(s);
return 0;
}
or maybe taking the filename from user in a string and then open that file for reading.
Thank You for reading.
Regards.
Jun 29, 2012 at 3:17pm UTC
Yes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
string str;
cout << "Enter file name to open: \n" ;
cin >> str;
ifstream in(str.c_str());
// do something
return 0;
}
Jun 29, 2012 at 3:19pm UTC
str.c_str();
What is that?
Please tell me...
Jun 29, 2012 at 3:24pm UTC
I thought strings worked as is, the important thing being "C:\CPP\try.cpp "
Jun 29, 2012 at 3:51pm UTC
I was trying the following exercise:
Create a Text class that contains a string object to hold the text of a file. Give it two constructors: a default constructor that takes a string argument that is the name of the file to open. When the second constructor is used, open the file and read the contents into the string member object. Add a member function contents() to return the string so (for example) it can be printed. In main(), open a file using Text and print the contents.
Based on useful info provided by modoran i came up with this code:
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
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
class Text{
string str;
public :
Text();
Text(string);
string contents();
};
Text::Text()
{}
Text::Text(string s)
{
ifstream in(s.c_str());
string temp;
while (getline(in,temp))
str += temp+"\n" ;
}
string Text::contents()
{return str;}
int main()
{
string newstr;
cin>>newstr;
Text txt(newstr);
newstr= txt.contents();
cout<<newstr<<endl;
return 0;
}
But this is not working. And as I dont know nothing about the function c_str().I dont know how to correct the code.
Any help is really appreciated.
Thank You for reading.
Regards.
Jun 29, 2012 at 4:08pm UTC
Well "This is not working" is quite generic... What does it do?
Jun 30, 2012 at 2:34am UTC
Sorry.. I tried with input:
"E:\CPP\try"
and
E:\CPP\try
but the program does not gives any output. There are no compiler or linker errors.
Topic archived. No new replies allowed.