I have the following source-code:
#include <stdio.h>
#include <time.h>
#include <string.h>
int main(int argc, char *argv[])
{
char string[100];
printf("Give me some text. \n");
fgets(string, 100, stdin);
char delimiter[]=" ";
char *erg;
erg=strtok(string, delimiter);
while(erg != NULL){
printf("Wort: %s \n", erg);
erg=strtok(NULL, delimiter);
}
return 0;
}
When I for example put in the text "abc def", the program is working like I want it to work. It print out the words "abc" and "def". But when I put in the text "abc def ", it prints out "abc", "def" and "". I don't want to print out the last empty "". Can someone please tell me how to filter that ?
Gruß, Andre
IMO, you need to get rid of the last \\n
read by fgets()
in fgets(string, 100, stdin);
You can do this in many ways, like
\\n
in your delimiter list. " \\n"
, for example. \\n
with a \\0
. fgets
gets a whole string along with the \\n
character which you press after entering the string.So use
string[strlen(string)-1]='\0';
to replace the \\n
in string
with a \\0
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.