【问题标题】:Using the member of a structure as validation使用结构的成员作为验证
【发布时间】:2017-06-25 17:16:31
【问题描述】:

我必须从 excel 文件中读取列,以便输出它的统计信息。我认为要做到这一点,我必须先创建一个struct。这就是我目前所拥有的一切。

#include <stdio.h>
#include <stdlib.h>


    /* Structure to store all the data that is required */
    typedef struct{
        char* id;
        int entryCount;
        int like;
        char gender[7];
    } statistics;

excel 文件是 facebook 的列表,如计数和成员姓名、ID 和性别。我的问题是,我如何使用if 语句来验证数据并找出点赞数是否属于male 或female 性别?

任何帮助将不胜感激。

编辑:使问题更清晰(我希望如此)。

【问题讨论】:

  • 除了typedefs 和if 语句之外,还有更多代码可以从excel 文件中读取内容......也许你会strcmp gender 反对@ 987654330@ 或 "female" - 但请注意 char gender[6] 太小,无法容纳 "female" + 空终止符。
  • 你的问题不是很清楚。在为表中的每行实例化一个结构后,您的目标到底是什么?
  • 附注,gender[6] 将不包含 female,当您计算将在末尾附加的空字符“\0”时。
  • @Idle001 strncmp 是首选。更安全!
  • @Noob 你更关心的应该是如何解析 excel 文件。一种简单的方法是使用 excel 到 csv 解析器来读取文件,写入 csv 文件,然后使用类似的解析器将输出文件转换为 excel。

标签: c excel


【解决方案1】:

比较字符串(实际上是字符数组,以'\0'结尾)的方法是使用正确的函数。

这是一个使用strncmp(...)的示例。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


/* Structure to store all the data that is required */
typedef struct{
    char* id;
    int entryCount;
    int like;
    char gender[7];
} statistics;

int main(void)
{
    statistics ExampleMale={"1", 2, 0, "male"};
    statistics ExampleFemale={"0", 1, 0, "female"};

    // Whatever you do to fill your structs is simulated by init above.
    if(strncmp(ExampleMale.gender,"male", 7))
    {
        printf("Male looks female.\n");
    } else
    {
        printf("Male looks male.\n");           
    }

    if(strncmp(ExampleFemale.gender,"female",7))
    {
        printf("Female looks male.\n");
    } else
    {
        printf("Female looks female.\n");           
    }

    return 0;

}

输出:

Male looks male.
Female looks female.

出于学习目的,我建议进行实验。
例如,尝试将结构内的字符串更改为“女性”和“男性”。
在这种情况下,我编写代码的方式将产生启发性的结果。 :-)
(归功于 Idlle001)

【讨论】:

  • 感谢您的回答。那么statistics ExampleMale={"1", 2, 0, "male"}; 是我输入的数据吗?如何使用 fopen 从文件中获取统计信息?另外,if语句中的7是什么意思?
  • 是的,它可以模拟您以任何您喜欢的方法读取的数据。通过使用 fopen() 来获取它,是的,但随后使用从文件中读取的函数 (sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html)。 7 是 strncmp() 的第三个参数,请阅读规范(例如 en.cppreference.com/w/c/string/byte/strncmp)并可能与代码中的其他数字进行比较。 ;-)
  • 感谢来源。如果7是要比较的字符数,第一个if语句不应该不等于7吗?
  • 7 是要比较的最大字符数。它对于避免函数在所有内存中乱跑非常有用。如果逻辑上需要,它也可以用于仅比较较长字符串的前几个字符。顺便说一句,使用 7 包括 '\0',在这种情况下可以认为是可选的,其中诸如“femaleaux”之类的内容超出了范围。
猜你喜欢
  • 2022-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-15
  • 1970-01-01
相关资源
最近更新 更多