0

I am trying to accept a multi word string from user input on the console. My code looks like..

char fullPath[150];
char fileName[30];
char serviceName[50];
int portNum[6];
char ip[16];

printf("Enter full path where you want the file to be.\nExample: C:\\Users\n");
scanf("%s", fullPath);
CheckDirectory(fullPath);

printf("Enter what you want the file to be named. \nExample: test.exe\n");
scanf("%s", fileName);
CopyNewFile(fullPath, fileName, argv[0]);

printf("Enter RunKey Service Name:\n");
fgets(serviceName,49,stdin);

printf("Enter callback IP:\n");
scanf("%15s", ip);

printf("Enter callback port:\n");
scanf("%5s", portNum);

The Issue I run into is...

Enter RunKey Service Name:
Enter callback IP:
192.168.100.10
Enter callback port:
443

As you can see, it skips over the part where I should input the service name. I have tried using scanf like the other two inputs and I have tried using regex expression (%[^\n]) as well and it does not grab the entire line either.

Edit: After more testing I am able to input into the Service name if I move the printf and scanf above the printf that asks where the file should be.

Brian Jarcus
  • 69
  • 1
  • 1
  • 6

1 Answers1

1

The thing is in the previous input scanf the entered \n is still in stdin - not the fgets in the next line consumed it. Put a dummy getchar() to get rid of it.

printf("Enter what you want the file to be named. \nExample: test.exe\n");
scanf("%s", fileName);
getchar();//<----

Another thing is portNum is of type int -you can't use %s format specifier to read into an int variable - this is undefined behavior. (Not passing the correct type of parameter as demanded by format specifier in scanf).

Also you can use fgets(serviceName,50,stdin); fgets will read it as per it's capacity - no need to limit it yourself.

Another thing is check the return value if scanf and fgets.


To be more clear - when getting string input why use the scanf instead of fgets - you can use simply fgets and get the input into it. Also another point is check the manual for scanf and fgets. To give you an example of how the return value should be checked for scanf and fgets.

if( scanf("%s", fileName)!= 1){
    fprintf(stderr,"%s\n","Error in input");
    exit(EXIT_FAILURE);
}

And in this way also for fgets

if( fgets(serviceName, 50, stdin) == NULL ){
    fprintf(stderr,"%s\n","Error in input");
    exit(EXIT_FAILURE);    
}
user2736738
  • 30,591
  • 5
  • 42
  • 56