I use fgets to take in a string of 3 commands seperated by spaces. when either 2
ID: 3542813 • Letter: I
Question
I use fgets to take in a string of 3 commands seperated by spaces. when either 2 or 3 commads are entered the if statement works fine, but if the user only puts in one command and hits enter the if statement fails even if true, unless a space is entered after the command and before enter
fgets(commandS, sizeof(commandS), stdin);
string seperated character by character into 3 strings. arg being first one
if(strcmp(arg,"command")==0){//not going in if statement condition problems
set(N,V);
return;
}
can ANYONE TELL ME WHY THIS IS HAPPENING?
Explanation / Answer
from what i understood the solution you want may be something like splitting string .
you may be splitting based on space but you need to split even if you encounter a i.e.new line character .i.e the code looks like
fgets(commandS, sizeof(commandS), stdin);
char *p = strtok(commandS, " "); //split using a space or new line , strtok takes regex = " " so it splits a string whenever it encounters a space or a new line which you want in your program when you enter a only one command without space there we have a new line so we split it and stor in arg which works fine then
while(p != NULL) {
printf("%s ", p);
p = strtok(NULL, " "); //strtok has an internal state variable tracking the string being tokenized. When you pass NULL to it, strtok //will continue to use this state variable. When you pass a non-null //value, the state variable is reset. So in other words: passing NULL means "continue tokenizing the same string"
}
//so here arg is first command so p[0] string seperated character by character into 3 strings. arg being first one
if(strcmp(p[0],"command")==0){//goes in now
set(N,V);
eturn; }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.