LearnFrenzy
Sign in Take a free test

Strings · Predict the Output · Question 6

strtok() token count and the changed string Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

What is the output of the following C program?

main.c
#include <stdio.h>
#include <string.h>

int main(void) {
    char line[] = "a,,b,c";
    int n = 0;
    for (char *t = strtok(line, ","); t != NULL; t = strtok(NULL, ","))
        n++;
    printf("%d %s\n", n, line);
    return 0;
}
  • A 4 a,,b,c
  • B 3 a Correct
  • C 3 a,,b,c
  • D 4 a
Correct Answer: Option B

strtok() treats consecutive commas as one separator, so the tokens are a, b and c: 3. It also wrote '\0' after "a", so printing line now shows only "a".

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links