我正在尝试传递一个数字和一组字符串
S
作为输入。这里,字符串 S
包含一个名称,后跟一个逗号,然后是一个多位整数 k
。程序必须显示对应数字最大的名称。
考虑以下一组输入: 4 威尔,13 鲍勃,7 玛丽,56 盖尔,45 其输出必须是: 玛丽 因为
Mary
对应的数字是56
,它是最高的。
我面临的问题是获取两个数组中的姓名和号码
w[][] a[][]
这里我尝试了二维数组,但我无法读取逗号分隔的值。
这是我的代码:
#include <stdio.h>
#include <ctype.h>
int main() {
char W[200][1000]; // Two dimensional arrays to store names
int a[200]; // To store the numbers
int i, n, max, pos;
scanf("%d", &n); // Number of Strings
for (i = 0; i < n; i++) {
scanf("%[^\n]s", W[i]); // To read the name
getchar(); // To read the comma
scanf("%d", &a[i]); // To read the number
}
printf("\n");
for (i = 0; i < n; i++) {
printf("W[%d] = %s a[%d] = %d\n", i, W[i], i, a[i]); // Displaying the values
}
// To find out the maximum value
max = a[0];
for (i = 0; i < n; i++) {
if (a[i] >= max) {
max = a[i];
pos = i;
}
}
printf("\n%s", W[pos]); // Print the name corresponding to the name
return 0;
}
所以基本上我想将逗号之前的名称提取到字符数组中,将逗号之后的数字提取到数字数组中。
如何更正此代码?
一般建议:更喜欢堆分配值(并使用
malloc
或 realloc
& free
;阅读有关 C 动态内存分配)而不是像 char W[200][1000];
这样的大变量。我建议处理一件char**W;
的事情。
程序必须显示对应数字最大的名称。
多想一点。您不需要存储所有以前读取的数字,并且您应该将程序设计为能够处理数百万行(名称、分数)的文件(而不占用大量内存)。
那么,
scanf("%[^\n]s",W[i]);
就是不做你想做的事。仔细阅读scanf
的文档(并测试其返回值)。使用 fgets
- 最好使用 getline
(如果有的话)- 读取一行,然后解析它(也许使用 sscanf
)。
所以基本上我想将逗号之前的名称提取到字符数组中,将逗号之后的数字提取到数字数组中。
和考虑使用标准的
lexing
parsing 技术,也许在每一行上。 PS。我不想做你的作业。
这是我的工作代码:
#include<stdio.h>
#include<stdlib.h>
int main()
{
char *str[100];
int i,a[100];
int num=100;//Maximum length of the name
int n,max,pos;
scanf("%d",&n);//Number of strings
for(i=0;i<n;i++)
{
str[i]=(char *)malloc((num+1)*sizeof(char));//Dynamic allocation
scanf("%[^,],%d",str[i],&a[i]);
}
max = a[0];
pos = 0;
for(i=1;i<n;i++){
if(a[i]>max) {max = a[i]; pos = i;}
}
printf("%s\n",str[pos]);//Prints the name corresponding to the greatest value
return 0;
}
我已经使用 malloc 动态存储字符串的内容。此外,我还使用 scanf() 进行格式化以获取单独数组中的字符串和数字。但是如果有更好的方法来执行相同的操作,那就是真的很棒。