【发布时间】:2017-03-19 14:09:11
【问题描述】:
我正在尝试传递一个数字和一组字符串 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);
}
所以基本上我想把逗号前面的名字提取到字符数组中,把逗号后面的数字提取到数字数组中。
如何更正此代码?
【问题讨论】:
标签: c string integer string-formatting