我试图传递一个数字和一组字符串 S 作为输入。这里的字符串 S 包含一个名称,后跟一个逗号,然后是一个多位整数。程序必须显示对应数字最大的名称。
考虑输入:
4
Will,13
Bob,7
Mary,56
Gail,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;
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) { a[i] = max; pos = i; }
}
printf("\n%s",W[pos]); //Print the name corresponding to the name
return(0);
}
所以基本上我想将逗号之前的名称提取到字符数组中,将逗号之后的数字提取到数字数组中。
如何更正此代码?
最佳答案
一般建议:与大型变量相比,更喜欢堆分配值(并使用 malloc
或 realloc
和 free
;阅读 C dynamic memory allocation )如char W[200][1000];
。我建议处理 char**W;
事情。
The program must display the name with the highest corresponding number.
多想一点。您不需要存储所有以前读取的数字,并且您应该将程序设计为能够处理数百万行(名称、分数)的文件(而不占用大量内存)。
然后,scanf("%[^\n]s",W[i]);
没有做你想做的事情。仔细阅读 documentation of scanf
(并测试其返回值)。使用 fgets
- 最好使用 getline
如果你有它-读取一行,然后解析它(也许使用sscanf
)。
So basically I want to extract the name before the comma into the character array and the number after the comma into the number array.
考虑使用标准lexing和 parsing技术,也许在每一行。
PS。我不想做你的作业。
关于c - 如何读取逗号分隔字符串中的名称和整数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42887555/