c - 我的代码没有正确打印名称。它只打印第一个单词的第一个字母,然后输入其余的
问题描述
#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
解决方案
打印时不需要&符号,因为数组的名称是指向数组第一个元素的指针。因此,请在打印数组时尝试删除 & 符号。
其次,如果要存储“字符串”,则需要使用二维数组,然后将每个“字符串”存储在该数组的每一行中。
例如。char x[1][4] ={"Jack"} => x --> 'J'|'a'|'c'|'k'|
有用的链接 --> https://www.knowprogram.com/c-programming/2d-array-of-strings-in-c/
推荐阅读
- java - 使用自定义 Jar 时编译 Maven 项目会引发错误
- java - 解析参数后内联优化算法速度
- java - JPA NamedQuery 不在 Glassfish4 中(但在 Glassfish3 中有效)
- reactjs - isomorphic-style-loader - 如何添加“活动”类
- angular - Angular2+:从类(不是组件)调用提供者
- dynamics-crm - OneLogin + Dynamics 365 通过代码进行身份验证
- lua - Roblox Studio - GUI 的按键切换
- angular - 如何将上下文传递给 Angular 4 中 *ngIf 的 else 分支?
- python - scikit-learn 和 scipy 库之间的确定系数不同。为什么?
- java - 如何在另一个方法之后调用方法?