Open file(ifstream)

Goodmorning, could you tell me what mistake I made in this code?

Because if I input "date.txt" the file is opened and analyzed completely, instead, if I input "date"... In my mind he must try to open date, but he might failed, so he entered in if and there he must try to open date.txt... But when I run the program it's not exit for error... But also when I try to write what i have into the file it's write just... "w"... Instead into the file i gota a phrase like "Roma is the better ...
Spiderman

Spider-man"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  char percorso[36]; 
cout<<"Nome del file da controllare: "; 
cin.get(percorso,32); 
cin.clear(); 
cin.ignore(256, '\n'); 
ifstream newf(percorso); 
if(newf.fail()) 
{ 
newf.clear(); 
strcat(percorso,".txt"); 
ifstream newf(percorso); 
if(!newf) 
{ 
cout<<"L'apertura del file e' fallita, il programma terminera'"; 
exit(-1); 
} 
} 


p.s. Yes I need to use the C-string. Not C++.
Tell me if you don't understand something, since I don't speak in english well ^^"
Indent your code. It helps. You need to learn about visibility and lifetime.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
ifstream newf(percorso); //Creates first newf variable and opens percorso file
if(newf.fail()) 
{ 
    newf.clear(); 
    strcat(percorso,".txt"); 
    ifstream newf(percorso); //Creates second newf variable and opens percorso file
    //Shadows previous newf variable. from this point all references to newf reference this variable
    if(!newf) //Checks second newf
    { 
        cout<<"L'apertura del file e' fallita, il programma terminera'"; 
        exit(-1); 
    } 
} //Second newf goes out of scope and destroyed
//All references to newf are referenceing first newf again. 
Oh my god!! You right O_O"
How did I not notice such an error...
Thank you very much!
Topic archived. No new replies allowed.