读取一个数字,应该算作一个符号

Reads a number and should be counted as a symbol

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

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

./p6 < test/p6-testdata

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 来打印字符

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;
}

[编辑以用 %c 替换 %s]

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

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

简单的方法是从文件中读取数字(下面的示例读取 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;
}

例子Use/Output

$ 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: ##############

您可以简单地添加 FILE* 指针并打开(并验证文件是否打开),然后使用 fscanf 而不是 scanf 读取文件。

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