从文件中读取数据并插入到地图C++中
Read data from the file and insert into map 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 openn");
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 %sn", line.c_str());
return false;
}
}
else
{
printf("No namen");
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;
}
}
};
您可以使用
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 %sn", line.c_str());
return false;
}
}
else
{
printf("No namen");
return false;
}
}
return true;
}
strtok
是C遗留的东西。在新C++代码中可能应该避免使用它,因为它修改了正在分析的字符串,并且因为它假定字符串以 null 结尾。
使用std::string::find_first_of
和std::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 namen";
return false;
}
auto name_end = line.find_first_of(" r", name_start);
if (name_end == std::string::npos)
{
std::clog << "No namen";
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 colorn";
return false;
}
auto color_end = line.find_first_of(" ", color_start);
if (color_end == std::string::npos)
{
std::clog << "No colorn";
return false;
}
std::string color{line, color_start, color_end - color_start};
std::cout << "color='" << color << "'n";
table[name] = std::move(color);
}
return true;
}
相关文章:
- 将一对插入地图并增加计数?
- 当我将其插入无序地图时,矢量的容量为 0
- 如何将元素插入到标准::地图的共享指针中?
- 无法插入到标准地图
- 为什么不插入地图?
- 为什么emplace_hint比插入地图慢?
- 地图插入(const_iterator提示,值)用法
- 无法将智能指针插入地图
- 插入到地图中,以对作为键并列出作为值
- 地图插入不明确
- VS 2017 错误 C2664 地图插入尝试
- 为什么通用参考概念不适用于函数指针的地图插入
- 地图插入将替换以前输入的值
- 地图插入密钥,但没有值
- 如何在CPU和内存中优化C 中的重型地图插入
- 我如何将MPL地图插入
- 地图::插入正在中断
- 我不明白地图插入上的此错误
- C++ 多重地图插入功能
- 地图插入返回错误答案的地图