你好我有一個小問題,我試圖從成員函數爲我的類的某些成員變量賦值。一切似乎都很好,但是一旦我的程序返回到EAN :: read(...);現在在成員變量 - >「╠╠╠╠╠╠」中有怪異的字符。任何人都可以向我解釋我做錯了什麼?謝謝。會員變量不保存從添加到它的成員從函數
///My class ////
class EAN
{
char string[13];
char strStyle[18];
char styles[2];
char area[6];
char publisher[8];
char title[8];
bool registered;
public:
///and member functions here//
};
////First member function that is called///
bool EAN::read(std::istream& is, const Prefix& list){
char str[13];
bool keepgoing = false;
do{
cout << "Enter a EAN(0 to quit): ";
is >> str;
if (str == nullptr || strlen(str) < 13){
keepgoing = false;
registered = false;
}
else{
keepgoing = true;
EAN(str, list); ///this is where member variable will be assigned//
registered = true;
std::cout << "this is area" << area << endl;
}
} while (keepgoing == false);
return keepgoing;
}
////////Here is the constructor that assigns the values to member variable//
EAN::EAN(const char* str, const Prefix& list){
int keepgoing = 0, j = 3, i = 0;
string[13] = '\0';
strStyle[18] = '\0';
area[6] = '\0';
publisher[8] = '\0';
title[8] = '\0';
if (isValid(str) == 1 && str[0] == '9' && str[1] == '7'|| str[2] == '8' || str[2] == '9') {
keepgoing = 1;
strcpy(string, str);
if (isRegistered(list) == true){
char _area[6];
int lengthArea = 0;
while (i < 5) {
_area[i] = str[j];
_area[i + 1] = '\0';
if (list.isRegistered(atoi(_area))) {
strcpy(area, _area); **<--- ///assign value to member variable.///**
lengthArea = strlen(area);
i = 6; // exit loop
keepgoing = 1;
}
else
{
i++;
j++;
}
}
.......more coding pretty same as above.
}
「成員變量不保存從函數中的成員向其添加的值」 - 用一個詞:**廢話**。問題幾乎總是很簡單。拿出一個* short *例子。 –
你使用C風格的字符串(char數組)而不是std :: string的任何原因? – ssell
如果你想在C++中使用字符串,你應該使用[標準字符串類](http://en.cppreference.com/w/cpp/string/basic_string)。 –