Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
This has been really bothering me, can someone pls help me out. I am trying to read-in a single character from stdin in my C program, so it ignores the '\n'. How do i go about it?? Help pls
thanx

for(;;){
menu();
scanf("%c", &choice);
switch(choice){
case '1': printf("Read File\n");
printf("Enter the name of input file: ");
scanf("%s", &filename);
infile = fopen(filename,"r");
ch = fgetc(infile);
while(ch != EOF){
printf("%c", ch);
ch = fgetc(infile);
}
fclose(infile);
break;
case '2': printf("Insertion\n");
break;
case '3': printf("Shell\n");
break;
case '4': printf("Print List\n");
break;
case '5': printf("Done!\n");
exit (0);
break;
default: printf("ERROR");
}
}That is my code, problem is everytime i read in something, the menu shos up twice, supposedly because its reading the "return" with it.

filename is a character array yes? You don't use the address operator with the scanf statement. A better choice in place of scanf is fgets IMO.
filename most likely would pick up the newline left in the buffer from choice, so either use something like getchar() after reading choice or perhaps scanf("%c%*c", &choice).
I'm not sure what you're doing with the file access part, but you should be testing it before trying to use it.
if((file_ptr = fopen(fname, "f_attrib")) != NULL) /* use the file */
your default *should* also have a break statement.
HTH

U only want to use scanf when u expect different data types in a predefined format ie, and int followed by a string. And the scan.. functions always read an entire line (or scan upto the first \n char)
getc(stdin) or getchar() don't.
When reading string input I find fgets the best lib function.
proto:
char *fgets(char *buf, int buf_size, FILE *input_device) ;read (at most) 'buf_size' chars from 'input_device' into 'buf' and return 'buf'.
ie:
#define MAX_INPUT 256
#include <stdio.h>char input[MAX_INPUT+1] ;
if ( fgets(input, MAX_INPUT, stdin) != NULL ) {/* input array contains valid string */
}********** Notice that the array is declared to be size 1 larger than the buf_size value passed to the fgets function: U need 1 extra char for the null terminator. This is why fgets is superior to gets, NO overruns or seg faults!
the other difference is that fgets retains the newline char at the end while gets trims it away.
U can trim manually using:
input[ strlen(input) - 1 ] = NULL ;
or
*(input + strlen(input) - 1) = NULL ;depending on whether u like array or pointer notation (both compile to same code)

![]() |
WSH vs VBS?
|
SSL & ON Line payment...
|

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |