如何通过scanf读取文件中的不同行输入

如何通过scanf读取文件中的不同行输入,c,scanf,C,Scanf,我正在尝试使用scanf通过文件读取不同的输入行。我只能读第一行并存储它 这是我写的代码 #include <stdio.h> #include <string.h> int imageWidth, imageHeight, safeRegionStart, safeRegionWidth; main(void) { int i=0, j=0; int totalP, pixel, totalSafeP, concat;

我正在尝试使用scanf通过文件读取不同的输入行。我只能读第一行并存储它

这是我写的代码

#include <stdio.h>
#include <string.h>   

int imageWidth, imageHeight, safeRegionStart, safeRegionWidth;

main(void)
{       
    int i=0, j=0; 
    int totalP, pixel, totalSafeP, concat; 
    int unsigned r,g,b;

    scanf("%d %d %d %d", &imageWidth, &imageHeight, &safeRegionStart, &safeRegionWidth);
    totalP = imageWidth * imageHeight ;
    totalSafeP = imageHeight * safeRegionWidth;
    char arr[512][50];
    char arr1[imageWidth][imageHeight];

    printf("total # of pixels: %d\nTotal # of safe Pixels: %d\n", totalP, totalSafeP);

    memset(arr,0x0,sizeof(arr));


    while(i!=totalP)
    {
        i++;
        scanf("%d", &pixel);

        /*bit shifting to get r,g,b*/       
        int r = pixel << 8;
        r = (unsigned int)logicalRightShift(r, 24);

        int g = pixel << 16;
        g = (unsigned int)logicalRightShift(g, 24);

        int b = pixel << 24;
        b = (unsigned int)logicalRightShift(b, 24);
        //printf("%d) r:%d , g:%d , b:%d\n",i, r,g,b);
        fillDescription(arr, r, g, b);


    }/*End for scanning all pixels*/
}/*end main*/ 
#包括
#包括
int imageWidth、imageHeight、safeRegionStart、safeRegionWidth;
主(空)
{       
int i=0,j=0;
int totalP、pixel、totalSafeP、concat;
int无符号r,g,b;
scanf(“%d%d%d%d”、&imageWidth、&imageHeight、&safeRegionStart、&safeRegionWidth);
totalP=图像宽度*图像高度;
totalSafeP=图像高度*安全区域宽度;
char-arr[512][50];
字符arr1[imageWidth][imageHeight];
printf(“像素总数:%d\n安全像素总数:%d\n”,totalP,totalSafeP);
memset(arr,0x0,sizeof(arr));
而(i!=totalP)
{
i++;
扫描频率(“%d”,像素(&P);
/*位移位以获得r,g,b*/

int r=pixel您的代码正在从标准输入读取数据,而不是从文件读取数据。您的代码正在尖叫着要求进行错误检查,但在最佳情况下工作。下面是运行它的示例:

$ ./test 
1 2 3 4
total # of pixels: 2
Total # of safe Pixels: 8
12
13
$ 

基本上,不要忘记点击<代码> <代码>,<代码> SCANF函数逐行解析数据。

< P>正如Vlad Lazarenko所说,你正在从标准输入中读取数据。如果你想从一个文件中读取,你可以考虑使用。

< P>我建议不要使用SCANF(或FSCANF)来读取输入。使用其他方法(FFET等)读取输入。然后解析输出。可能是使用sscanf,也可能是使用其他系统。我看到人们直接使用scanf阅读时出现了太多错误。

+1:
scanf
众所周知,即使使用简单的文件也很难正确使用。我们实际上只是在参数行aka.out中输入文件