简体   繁体   English

将struct值与变量进行比较

[英]Comparing struct values against variable

I'm struggling to compare the contents of a struct to a variable. 我正在努力将结构的内容与变量进行比较。 There are 10 structs in array1 with the variables value and count. array1中有10个结构,带有变量value和count。 I need to go through every value variable until I find the one matching tempVal and then increment the corresponding count, then the search can end. 我需要遍历每个值变量,直到找到一个匹配的tempVal,然后递增相应的计数,然后搜索可以结束。 If it's not found the function will return -1. 如果没有找到,该函数将返回-1。

I have the following code that runs fine but doesn't work, I have a feeling it may be something wrong with the strcmp line but I'm not sure. 我有以下代码运行正常但不起作用,我有一种感觉strcmp行可能有问题,但我不确定。 Cheers for any input. 欢呼任何输入。

int valCheck(char *tempVal){

    int j;
    for(j=0;j<10;j++){
        if(strcmp(array1[j].value, tempVal) == 0){ 
            array1[j].count++; //increment its count
            break;

        }
    }
}

Edited full: 编辑完整:

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

struct values
{
    char value[64];
    int count;
};

struct values array1[100];

//check if value exists in array
int valCheck(char *tempVal)
{
    int j;
    for(j=0;j<10;j++)
    {
        if(strcmp(array1[j].value, tempVal) == 0)
        {
            array1[j].count++; //increment its count
            //return j; // <== return index of found element
        }
    }
    return -1;
}

int main()
{
    FILE * input;
    int i;
    char tempVal[] ="hello";
    input = fopen("random.txt","r");

    for (i=0;i<=10;i++) //go through the 10 elements in text file
    {
        //scan each word into a temporary variable
        // **** NOT COMPLETE, JUST USING TEMPWORD ASSIGNED FOR NOW

        int checkedVal = valCheck(&tempVal);

        //if wordCheck returns -1 add the word to the array
        //otherwise do nothing as a duplicate has appeared
        if(checkedVal == -1){
            fscanf(input, "%s",array1[i].value);
        }

        printf("WORD %i: %s ",i,array1[i].value);
        printf(" COUNT IS: %i", array1[i].count);
        printf("\n");
    }

    fclose(input);
    return 0;
}

Assuming the following: 假设如下:

  • Your array is properly allocated (either on the stack or dynamically) to be at-least-10-elements wide. 您的数组已正确分配(在堆栈上或动态分配)至少10个元素宽。
  • Your structure member value is a valid char * or fixed-length char[n] buffer. 您的结构成员value是有效的char *或固定长度的char[n]缓冲区。
  • The string data references by the value member of your structure is properly null-terminated. 结构的value成员引用的字符串数据正确地以null结尾。
  • The string data referenced by tempVal is valid and properly null-terminated. tempVal引用的字符串数据有效且正确地以null结尾。
  • You're aware that strcmp() compares case-sensitively 你知道strcmp()比较区分大小写
  • You're comment about 100 elements in the array and this code only checking the first ten (10) elements is intentional 您对数组中的100个元素进行了注释,此代码仅检查前 (10)个元素是故意的

My crystal ball tells me that ultimately you need to have your function actually return something. 我的水晶球告诉我,最终你需要让你的功能实际上返回一些东西。

int valCheck(char *tempVal)
{
    int j;
    for(j=0;j<10;j++)
    {
        if(strcmp(array1[j].value, tempVal) == 0)
        { 
            array1[j].count++; //increment its count
            return j; // <== return index of found element
        }
    }
    return -1;  // <== return -1 per your description of failure.
}

Note: Your compiler, equipped with decent warning-checks, would easily spot this lack-of-return code. 注意:您的编译器配备了不错的警告检查功能,可以轻松发现这种缺乏返回的代码。 Heed those warnings. 注意那些警告。 Likewise, double-check everything in the bullet list at the top of this answer to make sure what you're going into this with is proper. 同样,仔细检查此答案顶部的项目符号列表中的所有内容,以确保您正在使用的内容是正确的。


EDIT Updated to reflect sample dictionary build for OP. 编辑更新以反映OP的示例字典构建。

The following is how I think this is likely to be called. 以下是我认为这可能会被调用的方式。 Hope it helps you. 希望它能帮到你。 I changed a few things: 我改变了一些事情:

  • Made the dictionary a little bigger (256) 使字典更大(256)
  • Processes the command line to get the filename. 处理命令行以获取文件名。 Makes it easier for me to test. 让我更容易测试。
  • Only reports a summary at the end rather than per-word while processing. 仅在处理时报告最后的摘要而不是每个单词。

I hope it helps. 我希望它有所帮助。

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

struct values
{
    char value[64];
    int count;
};

// global array.
struct values array1[256];
int n_words = 0;

//check if value exists in array
int valCheck(const char *tempVal)
{
    int j;
    for(j=0;j<10;j++)
    {
        if(strcmp(array1[j].value, tempVal) == 0)
        {
            array1[j].count++; //increment its count
            return j;
        }
    }
    return -1;
}

int main(int argc, char *argv[])
{
    FILE * input = NULL;
    char tempVal[64];
    int i=0;

    if (argc < 2)
    {
        printf("Must specify a filename.\n");
        return EXIT_FAILURE;
    }

    // open file
    input = fopen(argv[1],"r");
    if (!input)
    {
        perror("Failed to open file.");
        return EXIT_FAILURE;
    }

    // read all strings from the file one at a time.
    while (fscanf(input, "%64s", tempVal) == 1)
    {
        int i = valCheck(tempVal);
        if (i == -1)
        {
            if (n_words < sizeof(array1)/sizeof(array1[0]))
            {
                strcpy(array1[n_words].value, tempVal);
                array1[n_words].count = 1;
                i = n_words++;
            }
            else
            {   // error. no more space in dictionary
                printf("No more space to add word: %s\n", tempVal);
            }
        }

    }
    fclose(input);

    // summary report
    for (i=0;i<n_words;++i)
        printf("WORD %i: %s, COUNT IS: %i\n", i, array1[i].value, array1[i].count);

    return EXIT_SUCCESS;
}

Input 输入

hello my name is dave hello I am dave hi

Output 产量

WORD 0: hello, COUNT IS: 2
WORD 1: my, COUNT IS: 1
WORD 2: name, COUNT IS: 1
WORD 3: is, COUNT IS: 1
WORD 4: dave, COUNT IS: 2
WORD 5: I, COUNT IS: 1
WORD 6: am, COUNT IS: 1
WORD 7: hi, COUNT IS: 1

Homework 家庭作业

After all of that, I leave you to determine why the following code also works, but uses no temporary buffer to do so (sort of, anyway). 在所有这些之后,我让你确定为什么以下代码也可以工作,但是没有使用临时缓冲区(无论如何)。

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

struct values
{
    char value[64];
    int count;
};

// global array.
#define MAX_WORDS   256
struct values array1[MAX_WORDS] = {{{0},0}};
int n_words = 0;

//check if value exists in array
int valCheck(const char *tempVal)
{
    int j;
    for(j=0; j< n_words; j++)
    {
        if(strcmp(array1[j].value, tempVal) == 0)
        {
            array1[j].count++; //increment its count
            return j;
        }
    }
    return -1;
}

int main(int argc, char *argv[])
{
    FILE * input = NULL;
    int i=0;

    if (argc < 2)
    {
        printf("Must specify a filename.\n");
        return EXIT_FAILURE;
    }

    // open file
    input = fopen(argv[1],"r");
    if (!input)
    {
        perror("Failed to open file.");
        return EXIT_FAILURE;
    }

    // read all strings from the file one at a time.
    while (n_words < MAX_WORDS &&
           fscanf(input, "%64s", array1[n_words].value) == 1)
    {
        if (valCheck(array1[n_words].value) == -1)
        {
            array1[n_words].count = 1;
            ++n_words;
        }
    }
    fclose(input);

    // summary report
    for (i=0;i<n_words;++i)
        printf("WORD %i: %s, COUNT IS: %i\n", i, array1[i].value, array1[i].count);

    return 0;
}

The output is the same as before. 输出与以前相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM