Click to See Complete Forum and Search --> : C and strings
wmHardRock
11-14-2000, 12:45 PM
Hel
Hi, guys. I have a little C program that asks for a name (support for white character), but when I print it, it also displays the return caracter. So if in input Vince, it would return something like:
Hello Vince
, how's it going?
How can I prevent that?
Verbed
11-14-2000, 12:59 PM
The return ( \r ) should be the last character in the string before the null terminating character ( \0 ). So, if the string was defined as an array ( char string[...] ), this should work:
string[strlen(string) - 1] = '\0';
wmHardRock
11-14-2000, 09:58 PM
#include <stdio.h>
#include <string.h>
main()
{
char nom[40];
printf("Salut! C'est quoi ton nom? ");
fgets(nom,40,stdin);
printf("Hyas %s! Comment ça va?",nom);
}
how'd you fix that?
Strike
11-15-2000, 12:37 AM
#include <stdio.h>
#include <string.h>
#define STRING_LENGTH 40
main ()
{
char nom[STRING_LENGTH];
printf("Salut! C'est quoi ton nom? ");
fgets(nom, STRING_LENGTH, stdin);
nom[STRING_LENGTH - 1] = '\0';
printf("Hyas %s! Comment ça va?",nom);
}
That's one way to do it (I like anything that acts as the size of an array to be a #define so I can change all instances of it later without having to hunt for numbers).
----edit----
Actually, that doesn't work. It might have to do with flushing buffers or something like that ... that's weird.
[This message has been edited by Strike (edited 14 November 2000).]
miller
11-15-2000, 03:42 PM
Strike:
The reason that doesn't work is because the end of the string isn't neccessarily at char 40.
wmHardRock:
You need to do a:
string[strlen(string) -1] = '\0';
like Verbed said.
Even better, since the name might or might not have the '\n' at the end:
if(string[strlen(string)-1] == '\n')
string[strlen(string)-1] = '\0';