c - 如何读取逗号分隔字符串中的名称和整数值?

标签 c string integer string-formatting

我试图传递一个数字和一组字符串 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);
}

所以基本上我想将逗号之前的名称提取到字符数组中,将逗号之后的数字提取到数字数组中。

如何更正此代码?

最佳答案

一般建议:与大型变量相比,更喜欢堆分配值(并使用 mallocreallocfree;阅读 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.

考虑使用标准lexingparsing技术,也许在每一行。

PS。我不想做你的作业。

关于c - 如何读取逗号分隔字符串中的名称和整数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42887555/

相关文章:

c - 不同线程中的全局变体是否意味着不同的变体?

c++ - 为什么文件范围静态变量必须被零初始化?

c# - 如何在 .Net 中有条件地格式化字符串?

xml - XSLT:使用 xsl:value-of - 我返回的是字符串还是单个字符串的节点集?

string - 如何使用 Lua 将 IP 地址转换为整数?

java - Java 编译器在混合数字类型时是否优化类型转换?

c - 错误的 Malloc() 三层结构?

c - "tearing"在部分程序注释中的使用

c - realloc - 将 int 转换为 char

Java整数到固定长度字节数组