简体   繁体   English

以某种方式显示输出

[英]Showing output in a certain way

I am trying to print out the ASCII values of all the characters in a text file. 我正在尝试打印出文本文件中所有字符的ASCII值。

int main(int argc, char* argv[]) {
        FILE *fp;
        int c;
        fp = fopen(argv[1], "r");
        while((c = fgetc(fp)) != EOF) {
                printf("%c %3d\n", c, (int)c);
        }
        fclose(fp);
        return 0;
}

Is it possible to show the output as shown below? 是否可以显示如下所示的输出?

r     a     n     d     o     m
114   97   110   100   111   109

Assuming the first word in my input file is 'random'. 假设输入文件中的第一个单词是“ random”。 Thanks 谢谢

Yes, as hexiecs said, it is very possible. 是的,正如hexiecs所说,这是很有可能的。 Asking how would be a much better question. 怎么会是一个更好的问题。 I am going to assume this is what you mean. 我要假设这就是你的意思。

Here is an example of how you might go about doing this: 这是您可能如何执行此操作的示例:

#include <stdio.h>
#define NEW_TERMINAL_LINE 10

void print_current_characters(char char_equivalents[]);

int main(int argc, char const *argv[]) {
  char char_equivalents[NEW_TERMINAL_LINE] = {0};

  int c;
  int i = 0;
  int final_position; /* Store the final position that we will use later
                       * to get the remaining characters in the buffer */

  FILE *file;
  file = fopen("file.txt", "r");
  if (file) {
    while ((c = getc(file)) != EOF) {
        if (i > NEW_TERMINAL_LINE - 1) {
          /* Every time the buffer fills up, we need to go to a new line
           * in the output as well (defined by NEW_TERMINAL_LINE).
           * Then we need to clear the buffer and make a new line 
           * to start off printing again!
          */
          print_current_characters(char_equivalents);
          int j;
          for (j = 0; j < sizeof(char_equivalents)/sizeof(char_equivalents[0]); j++) {
            char_equivalents[j] = 0; /* Clear the filled up buffer */
            i = 0;
          }
          printf("\n\n");
        }
        /* Print the character itself (we will print the ASCII when the buffer fills up) */
        char_equivalents[i] = c;
        if(char_equivalents[i] == '\n') {
          printf("\\n\t");
        } else if (char_equivalents[i] == '\t') {
          printf("\\t\t");
        } else if (char_equivalents[i] == ' ') {
          printf("[space]\t");
        } else {
          printf("%c\t", c);
        }
        final_position = i;
        i++;
    }

    /* Print any remaining characters in the buffer */
    print_current_characters(char_equivalents);

    fclose(file);
  }
  printf("\n");
  return 0;
}
void print_current_characters(char char_equivalents[]) {
  printf("\n");
  int i;

  for(i = 0; i < NEW_TERMINAL_LINE; i++) {
    if (char_equivalents[i] == 0 || NULL) {
      break; /* Don't print if there is nothing but 0s in the buffer */
    }
    if(char_equivalents[i] == '\n') {
      printf("\\n\t\t");
    } else if (char_equivalents[i] == '\t') {
      printf("\\t\t");
    } else {
      printf("%d\t", (int)char_equivalents[i]); /* Print the ASCII character */
    }
  }
}

With my previous edit, Jonathan Leffler and I were discussing what would happen if the buffer filled up since the original poster said in a comment: 在我之前的编辑中, 乔纳森·莱夫勒Jonathan Leffler)和我正在讨论自原始海报发表评论以来,如果缓冲区被填满会发生什么情况:

I am assuming the input file will have a maximum 1000 characters. 我假设输入文件最多包含1000个字符。

The output would be a very long line unless there were newlines after a certain amount of characters. 除非有一定数量的字符后出现换行符,否则输出将长。

We could just have an array with a maximum buffer of 1000, but we could also save more memory by just processing the file every x amount of characters. 我们可以有一个最大缓冲区为1000的数组,但是通过仅每x个字符处理一次文件,我们也可以节省更多的内存。 Here, after every NEW_TERMINAL_LINE number of characters, we can create a new line and print out the current buffer. 在这里,每隔NEW_TERMINAL_LINE个字符后,我们可以创建一个新行并打印出当前缓冲区。 Finally we can empty the buffer, and continue processing the characters. 最后,我们可以清空缓冲区,然后继续处理字符。 In fact, using this approach, the buffer is only limited by the available memory on the computer . 实际上,使用这种方法, 缓冲区仅受计算机上可用内存的限制

Say we want the maximum number of characters (and the corresponding ASCII values) on a line to be displayed as 10. The text file contains the string: random random random random random random random random [enter] (Hypothetically, the string could be much longer and the program would still display it neatly). 假设我们希望将一行中的最大字符数(以及相应的ASCII值)显示为10。文本文件包含以下字符串: random random random random random random random random [enter] (假设,字符串可能会很多更长的时间,程序仍会整齐地显示它)。 The output of this program looks like 1 : 该程序的输出看起来像1

r   a   n   d   o   m   [space] r   a   n   
114 97  110 100 111 109 32     114  97  110 

d   o   m   [space] r   a   n   d   o   m   
100 111 109 32     114  97  110 100 111 109 

[space] r   a   n   d   o   m   [space] r   a   
32     114  97  110 100 111 109 32     114  97  

n   d   o   m   [space] r   a   n   d   o   
110 100 111 109 32     114  97  110 100 111 

m   [space] r   a   n   d   o   m   [space] r   
109 32     114  97  110 100 111 109 32     114  

a   n   d   o   m   \n  
97  110 100 111 109 \n

if NEW_TERMINAL_LINE is set to 10 . 如果NEW_TERMINAL_LINE设置为10

  1. We end up storing the ASCII equivalents in an array named char_equivalents . 我们最终将ASCII等效项存储在名为char_equivalents的数组中。 For every character we come across, we store it in the array, and then we print it out followed by a tab. 对于遇到的每个字符,我们将其存储在数组中,然后将其打印出来,后跟一个制表符。

  2. Once the buffer array is full, we move down a line, loop through the array, and print out the ASCII values with formatting: 缓冲区数组填满后,我们向下移动一行,遍历数组,并使用以下格式打印出ASCII值:

    Since char s are essentially int s in disguise as ASCII, we simply typecast the char as an int . 由于char本质上是伪装成ASCII的int ,因此我们只是将char类型转换为int This will print out the corresponding ASCII value. 这将打印出相应的ASCII值。 Afterwards, we add a tab to make sure everything aligned with the line above. 然后,我们添加一个标签以确保所有内容都与上面的行对齐。 With this information, it is not difficult to loop through the array and print out the corresponding information. 有了这些信息,就不难遍历数组并打印出相应的信息。

  3. We finally reset the buffer, and print the blank new line seen after NEW_TERMINAL_LINE characters for clarity. 最后,我们重置了缓冲区,并为清晰起见在NEW_TERMINAL_LINE字符之后打印了空白的新行。

  4. The buffer is filled and reset until we have printed all of the characters in the file (the previous steps are repeated). 缓冲区将被填充并重置,直到我们在文件中打印了所有字符为止(重复前面的步骤)。

  5. In the end, sometimes the buffer isn't full so we never printed out the remaining ASCII equivalents for the last line in the output. 最后,有时缓冲区未满,因此我们从不为输出的最后一行打印出剩余的ASCII等价字符。 We simply call print_current_characters() again. 我们只需再次调用print_current_characters()


1 I don't really think this was the best way to format the code, but at the same time, I did want to honor the format that the original post asked for. 1我并不是真的认为这是格式化代码的最佳方法,但是与此同时,我确实想尊重原始帖子所要求的格式。

It will become more convenient if you process individual words instead of each characters. 如果您处理单个单词而不是每个字符,它将变得更加方便。 This way you can print each individual characters of the words first, and then print ASCII values of each characters the words next. 这样,您可以先打印单词的每个字符,然后再打印单词的每个字符的ASCII值。

You can do try something like this. 您可以尝试这样的操作。

int main(int argc, char* argv[]) {
    FILE *fp;
    int c;
    char line[100];  /* Buffer to hold each line */
    fp = fopen(argv[1], "r");
    /* get each line, and print each word of the line */
    while (fgets(line, 100, fp) != NULL) {
            line[strlen(line) - 1] = '\0';
            print_words(line);
    }
    fclose(fp);
    return 0;
}

/* print_words: print each word from line */
void print_words(char *line)
{
    char *word;

    /* get each word, and print them with ascii values */
    if ((word = strtok(line, " ")) != NULL)
            ascii_print(word);
    while ((word = strtok(NULL, " ")) != NULL)
            ascii_print(word);
}

/* ascii_print: print each char and its ascii values for a word*/
void ascii_print(char *word)
{
    int i, len;

    len = strlen(word);

    /* print the word */
    for(i = 0; i < len; i++)
            printf("%-4c", word[i]);
    printf("\n");

    /* print ascii values */
    for(i = 0; i < len; i++)
            printf("%-4d", word[i]);
    printf("\n");
}

Note that above program is not totally correct, and may produce buggy results in some test cases. 请注意,上述程序并非完全正确,在某些测试案例中可能会产生错误的结果。 However it shows the idea that it is easier if you process word by word, instead of character by character. 但是,它显示出这样的想法:如果逐字处理而不是逐字处理,则更容易。

Although, the code is simple, you may have to see manual pages of fgets() and strtok() if you are not familiar with them. 尽管代码很简单,但是如果您不熟悉它们,则可能必须查看fgets()strtok()手册页。

Briefly saying, fgets() gets a line from a file, and strtok() gets each word from a line. 简而言之, fgets()从文件中获取line ,而strtok()从一行中获取每个word For more info, you need to do man 3 strtok and man 3 fgets in Google (or in command line if using Unix-like machine). 有关更多信息,您需要在Google中进行man 3 strtokman 3 fgets的操作(如果使用类Unix机器,请在命令行中进行操作)。

您可以首先使用缓冲区在一行中记录输入,然后可以通过将缓冲区中的字符转换为下一行中的整数来显示输入的ASCII值。

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

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