2017-03-17 197 views
-3

我正在從文件(名稱顏色)中讀取數據,並將其插入到表中,並且當名稱匹配時,返回正確的顏色。如何在C++函數中返回字符串

如何在功能

class call_color 
{ 
public: 
std::map<std::string, std::string> table; 

bool read(std::string &fname) 
{ 
    std::ifstream ifs (fname, std::ifstream::in); 
    if(ifs.fail()) 
    { 
     printf("Cant open\n"); 
     return false; 
    } 
    return read(ifs); 
} 
bool read(std::istream &is) 
{ 
    for (std::string line; std::getline(is, line);) 
    { 
     char *name = strtok(const_cast<char*>(line.c_str()), " \r"); 

     if(name != nullptr) 
     { 
      char *color = strtok(nullptr, " "); 
      if(color != nullptr) 
      { 
       table[name] = color; 
      } 
      else 
      { 
       printf("No color %s\n", line.c_str()); 
       return false; 
      } 
     } 
     else 
     { 
      printf("No Name\n"); 
      return false; 
     } 
    } 

    return true; 
} 
std::string get_color(std::string name) 
{ 
    std::string color; 
    std::map<std::string, std::string>::iterator it; 
    it = table.find(name); 
    if (it != table.end()) 
    { 
    color = it->second; 
    } 

    return color; 
} 
}; 

它返回一個巨大的負值(-772802864)或任何名稱巨大正值返回一個字符串。但我期望得到一個字符串,如:scdscsdcs

+2

而你的問題是.....? – EdChum

+1

'0'不是有效的字符串... –

+0

拋出異常而不是返回0? –

回答

1

,如果你想返回一個空字符串,你應該在函數的末尾添加

return std::string(); 

另請注意,您的else子句包含錯誤的返回類型。 0不能轉換爲有效的std :: string。

0

這可能有幫助。

std::string get_color(std::string name) 
{ 
    std::string color; 
    std::map<std::string, std::string>::iterator it; 
    it = table.find(name); 
    if (it != table.end()) 
    { 
     color = it->second; 
    } 
    else if (name == "Terminate") 
    { 
     color = ''; 
    } 
    return color; 
} 
+3

您是否嘗試編譯自己的建議代碼? ''''代表什麼樣的字符? –

0

沒有與

table[name] = color; 

地圖table預計的std :: string對象都爲鍵和值的一個問題,但兩者namecolor是字符*。你應該這樣做:

table[str(name)] = str(color); 
+0

表[std :: string(name)] = std :: string(mark); --- ???不起作用 – Rasp

+0

什麼是標記?什麼不行?有沒有編譯錯誤,或者你會得到奇怪的結果? – mwhite

+0

它與顏色相同。錯字。 – Rasp