arrays - 如何通过 C 中的给定输入创建和打印字符串数组?
问题描述
我刚开始学习 C,但在获取输入以及如何使用它们方面存在一些问题。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int test_case;
scanf("%d\n",&test_case);
char arr[test_case][test_case];
//here, I tried to place values into array
for (int i = 0; i < test_case; i++) {
scanf("%s\n",&arr[i]);
}
//and print
for (int j = 0; j < test_case; j++)
printf("Case #%d %s\n", j+1, arr[j]);
return 0;
}
如您所见,在这段代码中,首先,我获取了 test_case 值,并使用该大小创建了一个数组 (arr)。但放置并没有按照我想要的方式进行。这就是结果。
3 ->test_case
123 -> 1st element
789 -> 2nd
456 -> 3rd
results
Case #1 123789456
Case #2 789456
Case #3 456
Process returned 0 (0x0) execution time : 10.155 s
Press any key to continue.
案例 #1 应该是 123,案例 #2 = 789,但我做不到。问题是我该怎么做?
解决方案
我真的不知道你的代码有什么问题。除了你的 scanf 中不需要 '\n'
scanf("%d",test_case);
虽然在这里你走一个简单的方法:
#include <stdio.h>
#include <stdlib.h>
int main() {
int test_case;
scanf("%d",&test_case);
char **arr;
arr= malloc(test_case*sizeof(char));
//here, I tried to place values into array
for (int i = 0; i < test_case; i++) {
arr[i]=malloc(test_case*sizeof(char));
scanf("%s",arr[i]);
}
//and print
for (int j = 0; j < test_case; j++)
printf("Case #%d %s\n", j+1, arr[j]);
return 0;
}
希望我有帮助!
祝你有美好的一天!
推荐阅读
- c# - EFCache CachingProviderServices 缺少静态实例属性
- javascript - “如何解决 Node JS 中未定义的 req.body”
- c++ - 如何为不同的类重用相同的实现方法
- kubernetes - Kubernetes 配置版本错误 - 您的配置文件使用旧的 API 规范:“kubeadm.k8s.io/v1alpha1”
- python - 在正则表达式测试器中读取 HTML 之间的正则表达式,但不适用于我的代码
- javascript - 如何获得正确的小时输出:带有 AM/PM 的 toLocaleString("en-US") 的 "2-digit"?
- java - 如何在Java中将假分数转换为带分数?
- javascript - 映射两个对象并连接在一起
- html - 如何在引导程序中的 div 内垂直居中图像?
- google-sheets - 根据列中下拉数据的选择有条件地格式化单元格