+ 1
I tried to open a file using a constant string as a parameter for open function. ifstream in(name.c_str()) but the program can't open the file . Any suggestions?
Need help with files
10 odpowiedzi
0
This is obviously not a constant string problem as the compiler produced the program. The most common mistake is a path problem. If you are using Windows please be aware that the backslash '\' that is used to separate parts of a path is interpreted as a so-called escape sequence as in '\n' for newline or '\t' for tab. In order to fix this, just put a double "\\" instead of a single path separator "\".
If the problem still persists, try to add some more detail so we can analyze better.
0
That part of code lookes like this:
string name;
cout<<"Enter the name of the file:";
cin>>name;
ifstream in(name.c_str());
if(in.is_open){
cout<<"Open!";
}
This is inside of a project. I didn't specified the path when I used projects. There is any problem with my code?
0
Andrei, the code you posted will not compile as is_open is a function that needs to be called (missing "()"). But this can't be the error as this would lead to a compiler error and you would not have a program. So, what is the error you get? File not found?
0
I forgot to put the round brackets . They exist in my code . The problem in here:
if(in.is_open()){
cout<<"open!";}
else{
cout<<"not open";
}
the program always show me the "not open" text. it means it executes the else statement which means the file is not open . Why?
0
is_open() just returns if the file is open or not. Therefore, it's not a problem in this part of the code. This file is just not open.
There might be multiple causes for that:
1.) the given path might be wrong
2.) the file is not opened by the commands uttered before.
3.) you are using SoloLearn C++ and files just don't work (well) on SoloLearn C++
Troubleshooting:
1.) is the *by far* the most common cause for this kind of problem. Therefore, make sure you give the right path. Have a path that is as simple as possible (and therefore less error-prone). One way to do that is to copy the input file to C:\ or to your home directory (Linux) and then provide an absolute path. Also, for testing, just define the path in the code, otherwise you will have to type the same stuff over and over again.
2.) You could go super explicit and use the open function on the ifstream... makes it a little bit more readable, too
0
thanks Stefan
0
No problem. :-) So does it work now?
0
yes :)))
0
Very good, I'm glad it worked. So was it number 1 or 2? :-)
0
I used both