【问题标题】:Reads a number and should be counted as a symbol读取一个数字,应该算作一个符号
【发布时间】:2023-04-06 21:35:01
【问题描述】:

我想编写一个程序,使用scanf() 从标准输入中读取数字列表(每行一个)并打印横向图表。

例如,我使用我创建的数据文件:

./p6

5:#####
40:####################################### 51:############################################### ###
...
26:########################## 46:#############################################
14:##############

这是我第一次尝试的代码:

int main ()
{

  int i;      //i is integer and s is symbol
  char s = '#'; //s is a character with symbol should be converted

  printf ("Enter an integer\n");
  scanf ("%d", &i);
  i = s; // i is an interger from input should be converted to s

  printf ("%d: %d\n", i, s); 

  return 0;
}

输出:

Enter an integer
35: 35

我不明白为什么或如何?

请帮帮我。

【问题讨论】:

  • 你有什么不明白的?
  • 您需要一个循环来在图表中重复该字母。

标签: c scanf symbols


【解决方案1】:

简单的方法是从文件中读取数字(下面的示例读取stdin),然后循环输出填充字符'#' 后跟换行符的次数。只要您从文件中读取有效的整数输入,就重复此操作。

一个简短的例子是:

#include <stdio.h>

#define FILL '#'

int main (void) {

    int n;

    while (scanf ("%d", &n) == 1) {     /* for each valid input */
        printf ("%2d: ", n);            /* output the number n */
        for (int i = 0; i < n; i++)     /* loop n times */
            putchar (FILL);             /* outputting FILL char */
        putchar ('\n');                 /* tidy up with newline */
    }

    return 0;
}

使用/输出示例

$ echo "1 3 5 10 12 18 14 11 9 4 2" | ./bin/graphsideways
 1: #
 3: ###
 5: #####
10: ##########
12: ############
18: ##################
14: ##############
11: ###########
 9: #########
 4: ####
 2: ##

或者你的号码:

$ echo "5 40 51 26 46 14" | ./bin/graphsideways
 5: #####
40: ########################################
51: ###################################################
26: ##########################
46: ##############################################
14: ##############

在使用fscanf 而不是scanf 读取文件之前,您只需添加FILE* 指针并打开(并验证文件是否打开)。

如果您还有其他问题,请告诉我。

【讨论】:

    【解决方案2】:

    打印 35:35 的原因是您首先将 # 复制到 i 中,然后将 s 和 i 都打印为整数 (%d)。 # 在 ascii 中是 35。

    打印字符的说明符是 %c。

    【讨论】:

      【解决方案3】:

      你需要某种循环来打印出'#'

      另外,你应该使用 %c 来打印字符

      int main ()
      {
      
      int i;      //i is integer and s is symbol
      int x;
      char s = '#'; //s is a character with symbol should be converted
      
      printf ("Enter an integer\n");
      scanf ("%d", &i);
      
      printf ("%d: ", i); 
      
      for( x = 0; x < i; x = x + 1 ){
          printf ("%c", s);  
      }
      
      printf ("\n"); 
      
      
      return 0;
      }
      

      [编辑以将 %s 替换为 %c]

      【讨论】:

      • 您不能将 %s 与字符一起使用。 s 不是字符串,所以 %s 是不正确的。
      • 你可以打电话给putchar('#')而不是char s = '#'; ...; printf ("%c", s);
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-06
      • 1970-01-01
      • 2017-12-16
      相关资源
      最近更新 更多