views:

267

answers:

4

i am trying to get some data from the user and send it to another function in gcc. the code is something like this.

printf("Enter your Name: ");
    if(!(fgets(Name, sizeof Name, stdin) != NULL)) {
        fprintf(stderr, "Error reading Name.\n");
        exit(1);
    }

However, i find that it has an \n character in the end. so if i enter John it ends up sending John\n. so how do i remove that \n and send a proper string.

+4  A: 

The slightly ugly way:

char *pos;
if ((pos=strchr(Name, '\n')) != NULL)
    *pos = '\0';

The slightly strange way:

strtok(Name, "\n");

There are others as well, of course.

Jerry Coffin
Careful with the strtok way...not thread safe
frankc
Any C runtime library that is thread aware (which is to say, most any that target a multi-threaded platform), `strtok()` will be thread safe (it will use thread local storage for the 'inter-call' state). That said, it's still generally better to use the non-standard (but common enough) `strtok_r()` variant.
Michael Burr
+3  A: 
size_t ln = strlen(name) - 1;
if (name[ln] == '\n')
    name[ln] = '\0';
James Morris
A: 
char name[1024];
unsigned int len;

printf("Enter your name: ");
fflush(stdout);
if (fgets(name, sizeof(name), stdin) == NULL) {
    fprintf(stderr, "error reading name\n");
    exit(1);
}
len = strlen(name);
if (name[len - 1] == '\n')
    name[len - 1] = '\0';
draebek
A: 

I stupidly forgot to pay attention to what language this thread was about. My solution was for PHP. My bad. If somebody could tell me how to delete a post I can get rid of this...

JKB
You are sure this is C?
pmr