【问题标题】:How to read a name and integer value in a comma separated string?如何读取逗号分隔字符串中的名称和整数值?
【发布时间】: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


    【解决方案1】:

    一般建议:更喜欢堆分配的值(并使用mallocreallocfree;阅读C dynamic memory allocation)而不是像char W[200][1000]; 这样的大变量。我建议处理char**W; 的事情。

    程序必须显示对应数字最大的名称。

    多想一点。您不需要存储所有先前读取的数字,并且您应该将您的程序设计为能够处理数百万行(名称、分数)的文件(不会占用大量内存)。

    那么,scanf("%[^\n]s",W[i]);没有在做你想做的事。 仔细阅读documentation of scanf(并测试其返回值)。使用fgets - 如果有的话最好使用getline - 读取一行,然后解析它(可能使用sscanf)。

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

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

    PS。我不想做你的作业。

    【讨论】:

    • 是的,我同意 scanf 不能使用的事实。事实上,我可以尝试使用 fgets() 。谢谢@Basile Starynkevitch
    • 我有一个使用 malloc 和 scanf() 格式的解决方案。您的建议会很棒@Basile Starynkevitch
    【解决方案2】:

    这是我的工作代码:

    #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() 来获取单独数组中的字符串和数字。但是如果有更好的方法来做同样的事情真的很棒。

    【讨论】:

    • 你不需要&lt;malloc.h&gt;(非标准)但&lt;stdlib.h&gt;(标准)使用malloc和朋友。
    • 你真的应该测试scanf的结果(它是扫描项目的计数)。顺便说一句,%n 控件到 scanf 可能有用。
    • 感谢@Basile Starynkevitch 提供的宝贵信息。将进行更改
    • 1) scanf("%[^,],%d",str[i],&amp;a[i]); --> 导致 Mary 被打印为 "\nMary"。应该遵循“使用fgets”的建议。 2) pos 的值是多少,如果名字的数字最大?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多