C++文件錯誤| 'strcmp' was not declared in this scope|


今天編寫C++代碼時,出現了錯誤,如下:

'strcmp' was not declared in this scope

 

代碼部分如下:

#include<iostream>
#include<string>
using namespace std;


//抽象產品類 男人
class Man
{
public:
virtual void makeM() = 0;
};
//具體產品類 白色男人
class WhiteMan : public Man
{
public:
void makeM()
{
cout << "I'm a white man."<< endl;
}
};
//具體產品類 黃色男人
class YellowMan : public Man
{
public:
void makeM()
{
cout << "I'm a yellow man." << endl;
}
};
//具體產品類 黑色男人
class BlackMan : public Man
{
public:
void makeM()
{
cout << "I'm a black man." << endl;
}
};

while (strcmp(t.c_str(), e.c_str()) != 0)
    {
        cout << "請輸入標識符 ( 首字母大寫 ):";
        cin >> t;
        if (strcmp(t.c_str(), y.c_str()) == 0)
        {
            man_y->makeM();
            woman_y->makeW();
        }
        else if (strcmp(t.c_str(), w.c_str()) == 0) {
            man_w->makeM();
            woman_w->makeW();
        }
        else if (strcmp(t.c_str(), b.c_str()) == 0) {
            man_b->makeM();
            woman_b->makeW();
        }
        else if (strcmp(t.c_str(), e.c_str()) == 0) {   //輸入exit退出系統
            cout << "退出" << endl;
        }
        else {
            cout << "輸入的標識符有誤,請重新輸入!" << endl;
        }
        cout << endl;
    }

經過在網上查詢得知:

1.必須再加上#include <string.h>才能正確編譯執行,即同時存在 

#include<iostream>
#include<string>
#include <string.h>
using namespace std;

也就是說strcmp不在C++標准庫中,需要單獨包含strcmp所在的頭文件。

2.或者加上#include <cstring> ,即c的標准庫中也包含這個函數

#include <cstring>  
using namespace std;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM