首页 > 解决方案 > 我的代码没有正确打印名称。它只打印第一个单词的第一个字母,然后输入其余的

问题描述

#include <stdio.h>
        #include <stdlib.h>
        #include <math.h>
        
        int main() {
          int numcand;
          char name[numcand];
          int numregion;
          int votes[numregion][numcand];
          
          printf("Enter the number of candidates : ");
          scanf("%d", &numcand);
        
          for(int i=1; i<=numcand; i++){
            printf("Enter the name of candidate #%d : ", i);
            scanf("%s", &name[i-1]);
          }
        
        
          printf("Enter the number of regions : ");
          scanf("%d", &numregion);
        
        
          for(int i=0; i<=numregion; i++){
            for(int j=0;j<=numcand; j++){
              printf("Number of people who voted for %s : ", &name[i]);
              scanf("%d", &votes[j][i]);
            }
          }
        
        
        
          return 0;
        }

在第 26 行,我使用 %s 打印了第一个数组,但它打印了名字的第一个字母,其余的都与它一起打印。例如,如果名称#1 是 dave,名称#2 是 sam,名称#3 是 juan。它将打印 dsjuan

标签: c

解决方案


打印时不需要&符号,因为数组的名称是指向数组第一个元素的指针。因此,请在打印数组时尝试删除 & 符号。
其次,如果要存储“字符串”,则需要使用二维数组,然后将每个“字符串”存储在该数组的每一行中。
例如。char x[1][4] ={"Jack"} => x --> 'J'|'a'|'c'|'k'|

有用的链接 --> https://www.knowprogram.com/c-programming/2d-array-of-strings-in-c/


推荐阅读