【问题标题】:query regarding sprintf() and scanf()关于 sprintf() 和 scanf() 的查询
【发布时间】:2014-02-26 19:04:49
【问题描述】:

举个例子

int i=10,j;

float b=3.14,c;

char str[30];

sprintf(str,"%d%f",i,b);

sscanf(str,"%d%f",&j,&c);

printf("%d  -----  %f\n",j,c);

输出:- 103 ----- 0.1400000

如您所见,最初是 i=10 和 b=3.14。

我想要 j=10 和 c=3.14 使用 sprint() 和 sscanf()。

我面临的问题是编译器分配了j=103 和c=0.140000。

有什么办法可以解决sscanf()这个问题?

【问题讨论】:

  • 加一个空格:将sprintf(str,"%d%f",i,b)改为sprintf(str,"%d %f",i,b)。
  • 替代方案:打印 b 及其符号 sprintf(str,"%d%+f",i,b);。回扫时,该标志将充当分隔符。 (尽管添加空间是最好的)

标签: c printf scanf


【解决方案1】:

给sprintf 加一个空格。变化:

sprintf(str,"%d%f",i,b)

到

sprintf(str,"%d %f",i,b)

另外:在这里使用snprintf 也会更安全:

snprintf(str, sizeof str, "%d %f", i, b)

【讨论】:

  • 那个空间实际上在做什么
  • 你的意思是说它分隔了值
  • 它充当输入的分隔符。
  • @JosephQuinsey : 给sprintf()加空格后,我还需要在sscanf()之间加空格吗
  • 快速回答,不。更长的答案:大多数格式说明符(臭名昭著的豁免 %c)会自动跳过空格。但经常会看到不必要的空格:例如,%s %s 与 %s%s 完全相同。
【解决方案2】:

最好的方法是将数字分开,使用不同的符号,但如果你知道第一个 int 是 2 个字符长,你可以指定它:

sscanf(str,"%2d%f",&j,&c);
//           ^^

【讨论】:

    【解决方案3】:

    你少了一个空格

    改变

    sprintf(str,"%d%f",i,b);
    

    到

    sprintf(str,"%d %f",i,b);
    
    #include <stdio.h>
    
    int main()
    {
        int i=10,j;
    
        float b=3.14,c;
    
        char str[30];
    
        sprintf(str,"%d %f",i,b);
    
        sscanf(str,"%d%f",&j,&c);
    
        printf("%d  -----  %f\n",j,c);
        return 0;
    }
    

    输出

    ~ > ./a.out
    10  -----  3.140000
    

    【讨论】:

      【解决方案4】:

      sscanf 中的%d 转换说明符将匹配str 指向的缓冲区中任意数量的连续数字字符,直到遇到无法匹配的非数字字符。这将导致浮点数的整数部分被读取为 int 值的一部分。因此,您必须有一种方法来分隔字符串str 中整数的结束位置和浮点数的开始位置。您可以将任何非数字字符作为标记来分隔 int 值和 float 值。

      int i = 10, j;
      float b = 3.14, c;
      char str[30];
      
      // a # to separate the two values, can be any non-numeric char so that it
      // is not mistaken for a digit in the int or float value
      
      sprintf(str,"%d#%f", i, b);  
      
      // match the separator character to read int and then float
      
      sscanf(str, "%d#%f", &j, &c);   
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-20
        • 1970-01-01
        • 2011-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-11
        • 1970-01-01
        相关资源
        最近更新 更多