简体   繁体   中英

How do I parse strings with the newline character in C?

I'm writing a shell and I'm using getline() with stdin from the keyboard to take commands. I'm having trouble tokenizing the inputs though. I tried using \\n as a delimiter in the strtok() function, but it seems not to be working.

For example, I included an if statement to check if the user typed "exit" in which case it will terminate the program. It's not terminating.

Here's the code I'm using:

void main() {
int ShInUse = 1;
char *UserCommand;   // This holds the input
int combytes = 100;
UserCommand = (char *) malloc (combytes);
char *tok;

while (ShInUse == 1) {
   printf("GASh: ");   // print prompt
   getline(&UserCommand, &combytes, stdin);
   tok = strtok(UserCommand, "\n");
   printf("%s\n", tok);

   if(tok == "exit") {
      ShInUse = 0;
      printf("Exiting.\n");
      exit(0);
   }
}
if (tok == "exit")

tok and exit are pointers, so you are comparing two pointers. This leads to an undefined behavior, since they don't belong to the same aggregate.

This is not the way to compare strings. Use rather strcmp .

 if (strcmp (tok, "exit") == 0)

As @Kirilenko stated, you can't compare strings using the == operator.

But that's not it. If you're using getline() you don't need to split the input to lines anyway as getline() only reads a single line. And if you did want to split the input to other delimiters, you'd have call strtok() in a loop till it returns NULL.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM