1. 程式人生 > 其它 >C++檔案錯誤| 'strcmp' was not declared in this scope|

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;