C++/C

Advertisement


Question
I have a problem  in my program
My code is :

char cPath[500];
char cPath[500];
printf("Enter the file name with it's path :");
scanf("%[^\n]",&cPath1);
strcpy(cPath,cPath1);

the scanf will take till a enter is pressed.
-> if user enters "enter key" with out typing anything, the strcpy line gives me an error . how to handle this. Please make me clear as soon as possible

Thanks and regards
Suresh

Answer
Dear Suresh:

Try this:
char cPath1[500] = { 0 } ;
char cPath[500];
scanf ( "%sn" , cPath1 );
if ( cPath1 [ 0 ] != 0 )
{
 strcpy ( cPath , cPath1 );
}

Make sure you clear cPath1:

Also the escape characters you put in the scanf statement do not look right.

before the scanf statement check what the scanf has put in the string.  If nothing or if you detect unexpected behavior, then do not strcpy.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Titus B. Ledbetter, Jr.

Expertise

C , MFC, Object Oriented, Artificial Intelligence

Experience

I have over ten years experience in the field of Computer Science, five years experience developing C/C++. I recently wrote a chess program using Object Oriented, C++, MFC.

Education/Credentials
Master's Degree Computer Science from Johns Hopkins

©2016 About.com. All rights reserved.