Monday, September 19, 2011

Renaming a file in C++, why can i not use user input as new file name?

int result;

char oldname[50];

char newname[50];



cout%26lt;%26lt;%26quot;Enter The file name to change: %26quot;;

cin.get( oldname, 50 );



cout%26lt;%26lt;%26quot;Enter The file name to change: %26quot;;

cin.get(newname, 50 );



result = rename( oldname , newname );

if ( result == 0 )

puts ( %26quot;File successfully renamed%26quot; );

else

perror( %26quot;Error renaming file%26quot; );



I am trying to change a filename by entering the filename then change it to whatever user wants the new filename to be.



I get error why i try to use user define newname. Why can't i change it from user input.



how would i be able to change newname to user input?



Thank you in advance.Renaming a file in C++, why can i not use user input as new file name?most likely because the get method is sort of uncooperative. There's a long explanation, but basically, you just need to put a line between them that tells the next one to ignore the endline character that the last get put out;



Try this:



int result;

char oldname[50];

char newname[50];



cout%26lt;%26lt;%26quot;Enter The file name to change: %26quot;;

cin.get( oldname, 50 );

cin.ignore( 1, '\n');



cout%26lt;%26lt;%26quot;Enter The file name to change: %26quot;;

cin.get(newname, 50 );



result = rename( oldname , newname );

if ( result == 0 )

puts ( %26quot;File successfully renamed%26quot; );

else

perror( %26quot;Error renaming file%26quot; );Renaming a file in C++, why can i not use user input as new file name?try using using this instead of what you have.



cout%26lt;%26lt;%26quot;Enter The file name to change: %26quot;;

cin.get(oldname,50,'\n');

cin.ignore();



cout%26lt;%26lt;%26quot;Enter The file name to change: %26quot;;

cin.get(newname,50,'\n');

cin.ignore();





Also make sure the .txt file you are trying to rename is actually in the same folder as your project file or where ever the .exe that is created.

No comments:

Post a Comment