结构元素比较 [英] comparison of structures elements

查看:101
本文介绍了结构元素比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,伙计们.

那是我程序的片段.我正在尝试从文件中读取结构,然后将每个结构的单词与用户输入的单词进行比较.但是,即使它们相同,程序也认为这是不正确的.我不知道该如何解决...感谢您的帮助.

Hello, guys.

That is the fragment of my program. I''m trying to read structures from file and then compare the word of every structure and the word that user have entered. But even they are the same the programs says that''s incorrect. I have no idea how to fix it... I will be very thankful for any help.

#include <iostream>
#include <fstream>
#include <string>
#include <cstring>

using namespace std;

struct card {
       char word[40];
       char translation [40];
};

card A = {"Wort", "word"};
card S;

int main () {

    //Structures are read to the array
    int i, length;

    string pavadinimas = "cards.txt";

    ifstream file (pavadinimas.c_str());
    if (!file)
    cerr << "Unable to open file" << endl;

    file.seekg (0, ios::end);
    length = file.tellg();
    file.seekg (0, ios::beg);

    i = length/sizeof(card);

    card *arr = new card [i];

    for (int k = 0; k < i; k++) {
    file.read((char *)&S, sizeof(card));
    arr [k] = S;
    }
    file.close();

    // Comparison

    int x = 0;
    char myWord [40];

    while (x < i)
        {
            cout << arr[x].translation << endl;

            cout << "Enter a word" << endl;
            cin >> myWord;

            strcpy (A.word, myWord);

            if (arr[x].word != A.word) {
                cout << "You are INCORRECT..!" << endl;
                cout << "The correct answer is " << arr[x].word << endl;
            }
            else {
            cout << "Correct!" << endl;
            }

            x = x + 1;
        }

        delete[] arr;
    return 0;
}

推荐答案

您正在尝试比较两个指针.它们指向一些不同的存储位置,因此指针具有不同的值.在这些地址上找到什么数据都没有关系.

字符串比较可以用strcmp完成,例如:
http://www.cplusplus.com/reference/clibrary/cstring/strcmp/ [ ^ ].

—SA
You are trying to compare two pointers. They point to some different memory locations, so the pointers have different values. It does not matter what is the data found at those addresses.

The string comparison can be done with strcmp, for example:
http://www.cplusplus.com/reference/clibrary/cstring/strcmp/[^].

—SA


这篇关于结构元素比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆