如何打印未知数量的结果?

时间:2013-03-03 04:41:47

标签: loops scanf printf

第一次发帖,也是C的初学者。我的问题是如何打印未知数量的结果?以此代码为例:

#include <stdio.h>

int main(void)
{
    int a,b,c;
    b=0;

    printf("Enter the number of terms: ");
    scanf("%d", &a);

    for(b=0; b<=a; ++a)
    {
        printf("\n\nEnter the value of each term: ");
        scanf("%d",&c);
    }

printf("\n\n%d",c);

    return(0);
}

我想打印最后输入的所有值,但Idk如何调整它以便打印1,2等值。

P.S。如何使用fprintf在while循环中执行此操作。

1 个答案:

答案 0 :(得分:0)

您将需要使用所谓的Array来存储数据。您可以将阵列视为具有不同抽屉的文件柜。每个抽屉都可以存储一个值,您可以通过参考其索引来访问该抽屉。

您可以在此处了解C中的所有数组: http://www.thegeekstuff.com/2011/12/c-arrays/

祝你好运!

编辑:以下是fprintf:

的示例
/* fprintf example */
#include <stdio.h>

int main ()
{
   FILE * pFile;
   int n;
   char name [100];

   pFile = fopen ("myfile.txt","w");
   for (n=0 ; n<3 ; n++)
   {
     puts ("please, enter a name: ");
     gets (name);
     fprintf (pFile, "Name %d [%-10.10s]\n",n,name);
   }
   fclose (pFile);

   return 0;
}
相关问题