搜索char数组

时间:2017-01-30 02:37:04

标签: c++

在CPP文件#1中,我试图遍历数组以查看是否有任何输入的名称与Mordor或the_Vale匹配(从CPP文件#2到底部),但是我的循环不起作用,我只知道如何遍历字符串数组,而不是字符串

#Header File#

#ifndef KINGDOM_H
#define KINGDOM_H
namespace westeros
{
    class Kingdom
    {
    public:  //Makes this class public to the rest of the code

        char m_name[32];
        int m_population;
        int count = 0;
};
    void display(Kingdom&);
    void display(Kingdom* k, int x);
    void display(Kingdom* k, int x, int z);
    void display(Kingdom* k, int x, char foo[]);
    }
    #endif



#CPP FIle #1#
#include <iostream>
#include "kingdom.h"


void display(Kingdom* k, int x, char foo[])
{
    int a = 0;
    int found = 0;

    cout << "Searching for kingdom " << foo << " in Westeros" << endl;
    for (a; a < x; a++)
    {
        if (k[a].m_name == foo)

//(strcmp(k[a].m_name) == 0)//Not working
        {
            cout << k[a].m_name << ", population " << k[a].m_population << endl;
            found = 1;
        }
    }
    if (found == 0)
    {
        cout << foo << " is not part of Westeros." << endl;
    }
}

}



## CPP File (main) #2##
#include <iostream>
#include "kingdom.h"

using namespace std;
using namespace westeros;

int main(void)
{
int count = 0; // the number of kingdoms in the array

               // TODO: declare the kingdoms pointer here (don't forget to initialize it)
Kingdom* pKingdoms = nullptr;


cout << "==========" << endl
    << "Input data" << endl
    << "==========" << endl
    << "Enter the number of kingdoms: ";
cin >> count;
cin.ignore();


pKingdoms = new Kingdom[count];


for (int i = 0; i < count; ++i)
{
    // TODO: add code to accept user input for the kingdoms array
    int x = 0;
    x++;
    cout << "Enter the name for kingdom #" << x + i << ": ";
    cin >> pKingdoms[i].m_name;
    cout << "Enter the number people living in " << pKingdoms[i].m_name << ": ";
    cin >> pKingdoms[i].m_population;

}
cout << "==========" << endl << endl;


// testing that "display(...)" works
cout << "------------------------------" << endl
    << "The first kingdom of Westeros" << endl
    << "------------------------------" << endl;
display(pKingdoms[0]);
cout << "------------------------------" << endl << endl;

// This is where I am having the problem
display(pKingdoms, count, "Mordor");
cout << endl;

display(pKingdoms, count, "The_Vale");
cout << endl;

cout << endl;

delete[] pKingdoms;
pKingdoms = nullptr;
return 0;
 }

1 个答案:

答案 0 :(得分:4)

  

if (k[a].m_name == foo)

这不是你比较两个C-Style字符串的方式。这只比较指针,几乎可以肯定会导致错误。您可以使用strcmp#include <string.h>):

if (!strcmp(k[a].m_name, foo))

更好的方法,因为您使用C ++进行编程,请使用std::string

std::string m_name;

并且比较完美无缺。