2015-04-04 128 views
0

因此,我环顾四周,发现%n一般信息很少,没有关于如何将它与变量一起使用的信息。%n如何与变量一起工作

据我可以告诉我使用的代码应该工作,但我不知道它不是什么。我遇到的特定行是:

printf("%d %n", num[x], &c); 

以下是整个代码。

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 

int main(void) 
{ 
     //seed rand, declare arrays, declare variables 
     srand(time(NULL)); 
     int num[10]; 
     int c = 0; 
     int total = 0; 
     int x; 

    printf("%s%14s%20s\n", "Value", "Characters", "Total Characters"); 

    //Loads the num array with random numbers. 
    for(x = 1; x < 10; x++) 
    { 
      num[x] = 1 + rand() % 1000; 
    } 

    for (x = 1; x < 10; x++) 
    { 
      printf("%d %n", num[x], &c); 
      printf("%14d", c); 
      total = total + c; 
      printf("%20d\n", total); 
    } 
} 
+1

[这里](http://stackoverflow.com/问题/ 3401156 /这是n-format-specifier-in-c的用法) – 2015-04-04 18:03:30

+0

很少的信息?在这里:https://msdn.microsoft.com/en-us/library/hf4y5e3w.aspx – 2015-04-04 18:08:42

+0

btw:在rand()的输出上计算_any_类型将统计减少它的随机性,您可以有效地生成伪随机数这是可预测的。 – specializt 2015-04-04 19:56:21

回答

2

从C标准

n中的参数应该是指向符号整数成是 写入由该呼叫到fprintf中写入到输出流到目前为止 的字符数。没有参数被转换,但一个是消耗的 。如果转换规范包含任何标志,宽度或精度字段,则行为未定义。

同样是有效用于printf

下面是一个示范程序

#include <stdio.h> 

int main(void) 
{ 
    int n1, n2; 

    printf("%s%n%s%n\n", "Hello", &n1, " World", &n2); 

    printf("%d\t%d\n", n1, n2); 

    return 0; 
} 

程序输出是

Hello World 
5 11 
+0

我读过这个,但我仍然遇到麻烦。我不知道我是否使用不正确的语法,或者我错过了什么。据我所知,从我发现的所有例子中,我正确地做到了这一点,但是我的输出结果如同没有任何东西存储在变量中一样。 – 2015-04-05 16:39:10

+0

@ s.lucas查看我的更新后的帖子,包括现在的例子。 – 2015-04-05 16:51:24

相关问题