c++ - 比较字符串c++的问题

标签 c++ string compare

<分区>

我刚从 C 转到 C++,发现比较字符串方法有困难。 我有一个简单的任务。我需要创建一个学校教师类,然后创建一个对象数组,并在撤消所有教师之后,谁的主题类似于testSubject。

这是我的课

class Teacher 
{
private:

    string FamilyName;
    string Name;
    string Patronymic;
    string sex;
    int exp;
    std::string subject;
    string speciality;
    int age;


public:

    Teacher(); 
    int getExp();
    string getSubject();
    int getAge();
    void show();

};    

这是我的功能,撤回教师列表,教授输入的主题

void ListTeacherSub (Teacher spis[], int n)
{
//List of teachers, who's subject is like testSubject
std::string testSubject;
cout<<"Enter test subject "; cin>>testSubject;
for (int i=0; i<n; i++)
{
    if (spis[n].getSubject().compare(testSubject) == 0)
        spis[i].show();
}        
}

这里是main()函数

int main() 
{
Teacher *spis;
int n;
cout<<"Enter numbers of student "; cin>>n;
spis = new Teacher[n];
for (int i=0; i<n; i++)
{    
 spis[i].show();
}

ListTeacherAge(spis, n);
ListTeacherEx(spis, n);
ListTeacherSub(spis, n);

 delete[] spis;
 return 0;
}

所以,一切都很好,但是当程序到达 ListTeacherSub(spis, n) 时它停止工作。据我所知,我过去只使用 strcmp,但不适用于字符串。 所以我决定寻找不同的实现,并找到了一个 http://www.cplusplus.com/reference/string/string/compare/

我该如何解决我的问题?

最佳答案

这个

if (spis[n].getSubject().compare(testSubject) == 0)

应该是

if (spis[i].getSubject().compare(testSubject) == 0)

关于c++ - 比较字符串c++的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26761160/

相关文章:

c# - 如果我们使用 NGen.exe 将其编译为 native 代码,C# 是否需要运行 .NET 框架?

ruby - 您可以对带有插值的字符串使用 ruby​​ 百分比表示法吗?

c# - 如何找到图像移动的像素数量?

Python 3 : applying recursion to compare lists?

在 C 中比较两次

c++ - 为什么 std::vector 和 std::array 的 C++ initializer_list 行为不同?

C++ 检查字符串是否包含至少 1 个数字和 1 个字母

c++ - 我正在测试 WM_MENUCHAR 但代码没有按预期工作

python - 在 python 中识别字符串中的子字符串的最有效方法?

c++ - std::string 在 std::cin 的 4095 个字符后被截断