开发者

Can you parse sentences with `scanf` and detect newlines?

开发者_运维问答I know how scanf could be used for parsing sentences into single words:

while(1){
    scanf("%s", buffer)
    ...
}

However, if I enter a sentence like one two three<return>, how can I find out inside a while-loop if the word I'm getting in the buffer is the one before I pressed <return>?

I guess it is hardly possible with scanf, but maybe there is a similar function?


You should use fgets() to read the whole line, and parse it like so:

char buffer[BUFSIZE] = {};        // BUFSIZE should be large enough for one line
fgets(buffer, BUFSIZE, stdin);    // read from standard input, same as scanf
char *ptr = strtok(buffer, " ");  // second argument is a string of delimiters
                                  // can be " ,." etc.
while (ptr != NULL) {
    printf("Word: '%s'\n", ptr);

    ptr = strtok(NULL, " ");      // note the NULL
}

Checking if the current word is the last word is trivial:

while (ptr != NULL) {
    char word[BUFSIZE] = {};
    strcpy(word, ptr);         // strtok clobbers the string it is parsing
                               // So we copy current string somewhere else.
    ptr = strtok(NULL, " ");

    bool is_last_word = (ptr == NULL);
    // do your thing here with word[]
}


If you're only interested in the last word, you can do it yourself reasonably easily. The fgets() solutions presented are prone to complication if lines exceed your buffer size - you may wind up splitting a word across multiple fgets() calls. You should be prepared to deal with that eventuality.

scanf() is dangerous on its own - it will read arbitrary length words into your buffer. Always remember to use %s with a length specifier if you rely on it. I'm pretty sure you can't actually use scanf() to achieve what you need though.

You are best to process the input character by character. When you hit a space you're at a word break. When you hit a newline you're at the last word.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜