【问题标题】:C-help understanding sscanfC-帮助理解sscanf
【发布时间】:2013-09-23 13:14:04
【问题描述】:

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

#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;
}

我可以将标有“行”的行替换为以下内容吗:

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

【问题讨论】:

    标签: c scanf


    【解决方案1】:

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

    所以,while ( (sscanf(&amp;s[idx], "%s%n", word, &amp;n) &gt; 0 ) 表示 while there is data being read, do this {}。

    在类型不匹配的情况下循环将中断(这将导致函数返回0)或在失败的情况下返回EOF(这是一个整数常量表达式负值 - 这也解释了为什么你不能只使用 while ((sscanf(&amp;s[idx], "%s%n", word, &amp;n)),因为在 C 中任何不同于 0 的值都被认为是 true 并且在 EOF 的情况下循环不会中断) .

    【讨论】:

    • 如何在开头跳过空格?
    • 该函数读取并忽略在下一个非空白字符之前遇到的任何空白字符(空白字符包括空格、换行符和制表符)。
    【解决方案2】:

    这是一个小翻译:

    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】:

      sscanf 从第一个参数中读取并以给定的格式写入。

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

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

      【讨论】:

        【解决方案4】:

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

        不,你不应该用

        替换该行

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

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

        【讨论】:

          【解决方案5】:

          看看这里: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
          

          【讨论】:

            猜你喜欢
            • 2014-11-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-09-20
            相关资源
            最近更新 更多