2017-03-17 11 views
-3

ファイル(名前の色)からデータを読み込んでテーブルに挿入し、名前が一致すると正しい色が返されます。それは巨大な負の値(-772802864)、または任意の名前のための巨大な正の値を返す方法機能で文字列を返すように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; 
} 
}; 

。あなたは空の文字列を返すようにしたい場合は、関数の最後に

return std::string(); 

を追加する必要がありますscdscsdcs

+2

あなたの問題は.....ですか? – EdChum

+1

'0'は有効な文字列ではありません... –

+0

0を返す代わりに例外をスローしますか? –

答えて

1

:しかし、私はのような文字列を取得するために期待しています。

また、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 ::文字列がキーと値の両方のオブジェクトを期待マップに問題がありますが、両方のnamecolorは、charです。

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

テーブル[std :: string(name)] = std :: string(mark); ---役に立たなかった – Rasp

+0

マークとは何ですか?何がうまくいかない?コンパイルエラーがありますか?または奇妙な結果が得られますか? – mwhite

+0

色と同じです。打ち間違え。 – Rasp

関連する問題