简体   繁体   English

当 c 程序运行时,打印大量的垃圾

[英]Prints garbage with lots of � when c program runs

I am trying to write a program that takes a file from the command line and then prints it out in a 2D array so that I can call specific elements.我正在尝试编写一个程序,该程序从命令行获取文件,然后将其打印在二维数组中,以便我可以调用特定元素。 I had a previous error because I closed the pointer in the loop instead of the main body but now that I've fixed that something else comes up when I run the program.我有一个先前的错误,因为我关闭了循环中的指针而不是主体,但现在我已经修复了运行程序时出现的其他问题。 It prints out the contents like I want but then after it prints out &�be���~����0��~�����~���0��~�'~�~�� 0��@�����~�� � � � ����� � hr ��0��~�@������~�M��o"V0U�~���o"V��o"V what am I doing wrong here?它打印出我想要的内容,但是在打印出 &�be���~����0��~�����~��0��~�'~�~�� 0 ��@������~�� � � ������� � hr ��0��~�@������~�M��o"V0U�~���o" V��o"V 我在这里做错了什么?

 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
 
 int main(int argc, char* argv[]){
      int i;
      int j;
      char tttInput[20][20];
      FILE *tttInputPtr = fopen(argv[1], "r");
    
      if (tttInputPtr == NULL) {
        printf("Unable to open file\n");
        return 1;
      }
      for(i=0; i<20; i++){
        for(j=0; j<20; j++){
          fscanf(tttInputPtr, "%c", &tttInput[i][j]);
        }
      }
      for(i=0; i<20; i++){
        for(j=0; j<20; j++){
          printf("%c", tttInput[i][j]);
        }
      }
      fclose(tttInputPtr);
      return 0;
    }
      for(i=0; i<20; i++){
        for(j=0; j<20; j++){
          fscanf(tttInputPtr, "%c", &tttInput[i][j]);
        }
      }
      for(i=0; i<20; i++){
        for(j=0; j<20; j++){
          printf("%c", tttInput[i][j]);
        }
      }

This loop will attempt to read 400 characters from the input and print them all.此循环将尝试从输入中读取 400 个字符并将它们全部打印出来。 But you don't have 400 so it prints garbage.但是你没有 400 所以它打印垃圾。

Solution: stop iteration on second loop after read failure解决方案:读取失败后在第二个循环上停止迭代

      int ni, nj;
      for(ni=0; ni<20; ni++){
        for(nj=0; nj<20; nj++){
          if (1 > fscanf(tttInputPtr, "%c", &tttInput[ni][nj]))
              goto break2; /* there has got to be a nicer way to break 2 loops at once */
        }
      }
;break2:
      for(i=0; i<=ni; i++){
        for(j=0; j<=((i == ni) ? nj : 20); j++){
          printf("%c", tttInput[i][j]);
        }
      }

I really feel there's a nicer way to break out of the two loops, and again I really feel there's got to be a nicer loop condition for the loop control of the inner loop.我真的觉得有一个更好的方法可以打破两个循环,而且我真的觉得内部循环的循环控制必须有一个更好的循环条件。

Maybe there is if you revealed why you used a two-dimensional array for the input.如果您透露了为什么使用二维数组作为输入,也许会有。 This particular code would be so much nicer without it, but it doesn't look like an accident.如果没有它,这个特定的代码会好得多,但它看起来不像是意外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM