从文件中读取数据并插入到地图C ++中

时间:2017-03-19 20:10:58

标签: c++

当我请求密钥时,它会给出一个巨大的负数(-7998482842)或正数(898395893),但它应该返回一个字符串。

文件格式:

string string
hello@gmail.com color1
hello@hotmail.com color2

我认为问题在于:table[name] = std::string(color);

有人可以帮忙吗?

class table_data
{
   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] = std::string(color);
            }
            else
            {
                printf("No data %s\n", line.c_str());
                return false;
            }
        }
        else
        {
            printf("No name\n");
            return false;
        }
    }

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

   }
};

2 个答案:

答案 0 :(得分:0)

您可以使用std::stringstream拆分该行:

#include <sstream>
//...
bool read(std::istream &is)
{
  for (std::string line; std::getline(is, line);)
  {
    std::string name, color;
    std::stringstream ss(line);
    if (ss >> name)
    {
      if(ss >> color)
      {
        table[name] = color;
      }
      else
      {
        printf("No data %s\n", line.c_str());
        return false;
      }
    }
    else
    {
      printf("No name\n");
      return false;
    }
  }
  return true;
}

答案 1 :(得分:0)

strtok是遗留的C事物。在新的C ++代码中可能应该避免它,因为它修改了正被解析的字符串,并且因为它假定字符串是空终止的。

如何使用std::string::find_first_ofstd::string::find_first_not_of

类似的东西:

bool read(std::istream &is)
{
  for (std::string line; std::getline(is, line);)
  {
    auto name_start = line.find_first_not_of(" \r");
    if (name_start == std::string::npos)
    {
      std::clog << "No name\n";
      return false;
    }
    auto name_end = line.find_first_of(" \r", name_start);
    if (name_end == std::string::npos)
    {
      std::clog << "No name\n";
      return false;
    }
    std::string name{line, name_start, name_end - name_start};
    std::cout << "name='" << name << "'\n";

    auto color_start = line.find_first_not_of(" ", name_end);
    if (color_start == std::string::npos)
    {
      std::clog << "No color\n";
      return false;
    }
    auto color_end = line.find_first_of(" ", color_start);
    if (color_end == std::string::npos)
    {
      std::clog << "No color\n";
      return false;
    }
    std::string color{line, color_start, color_end - color_start};
    std::cout << "color='" << color << "'\n";

    table[name] = std::move(color);
  }

  return true;
}