C-help了解sscanf

时间:2013-09-23 13:14:05

标签: c scanf

我很难理解标有“line”的行: -

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<ctype.h>

int main(void)
{
char s[81], word[81];
int n= 0, idx= 0;

puts("Please write a sentence:");
fgets(s, 81, stdin);
while ( sscanf(&s[idx], "%s%n", word, &n) > 0 )    //line
{
    idx += n;
    puts(word);
}

return 0;
}

我可以用以下内容替换标有“line”的行:

while ( sscanf(&s[idx], "%s%n", word, &n) )

5 个答案:

答案 0 :(得分:4)

sscanf函数返回值是成功读取的参数列表中的项数。

因此,行while ( (sscanf(&s[idx], "%s%n", word, &n) > 0 )表示while there is data being read, do this {}

如果类型不匹配(这将导致函数返回0EOF以防出现(这是一个负值的整数常量表达式 - 这也解释了为什么你不能仅使用while ((sscanf(&s[idx], "%s%n", word, &n)),因为在C中,任何与0不同的值都被视为true,如果是EOF {1}}循环不会中断

答案 1 :(得分:0)

sscanf函数返回成功填充的参数列表中的项数。如果While将返回正值,sscanf将被执行。

不,你不应该用

替换那一行

while ( sscanf(&s[idx], "%s%n", word, &n) )

因为如果输入失败,它将返回EOF这是一个非零值,使您的while条件为真。

答案 2 :(得分:0)

这是一个小翻译:

int words_read;
while (1) {

    // scscanf reads with this format one word at a time from the target buffer
    words_read = sscanf(
          &s[idx] // address of the buffer s + amount of bytes already read
        , "%s%n" // read one word
        , word // into this buffer
        , &n // save the amount bytes consumed inbto n
        );


    if (words_read <= 0) // if no words read or error then end loop
        break;

    idx += n; // add the amount of newlyt consumed bytes to idx

    puts(word); // print the word
} 

答案 3 :(得分:0)

sscanf从第一个论点中读取并以给定的格式写出来。

sscanf(string to read, format, variables to store...)

所以,只要 s 数组中有内容可读,sscanf就会读取它并存储在 word n 中。

答案 4 :(得分:0)

看看这里:sscanf explanation

从标准中取出80个字符,将它们存储在char []中,然后一次打印一个单词。

while ( sscanf(&s[idx], "%s%n", word, &n) > 0 ) //copy from "s" into "word" until space occurs
//n will be set to position of the space
//loop will iterate moving through "s" until no matching terms found or end of char array
相关问题