C++将文件内容读取到地图中
C++ reading contents from file into a map
我有一个文件,我想读入地图。
file.txt
temperature 55
water_level 2
rain 10
........
虽然我知道我可以使用 C 函数"sscanf"来解析数据。我更愿意用C++来做这件事(我只是习惯了这种语言(并将其读入地图(第一列作为键,第二列作为值(。
我尝试如下:
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <string.h>
#include <map>
using namespace std;
int main(){
const char *fileName="/home/bsxcto/Wedeman_NucPosSimulator/test/params.txt";
ifstream paramFile;
paramFile.open(fileName);
string line;
string key;
double value;
map <string, int> params; #### errors
while ( paramFile.good() ){
getline(paramFile, line);
istringstream ss(line);
ss >> key >> value; # set the variables
params[key] = value; # input them into the map
}
inFile.close();
return 0;
}
但是,在映射结构的初始化中,我得到了一堆错误:
Multiple markers at this line
- ‘value’ cannot appear in a constant-
expression
- ‘key’ cannot appear in a constant-expression
- template argument 2 is invalid
- template argument 1 is invalid
- template argument 4 is invalid
- template argument 3 is invalid
- invalid type in declaration before ‘;’ token
我也尝试过"地图"和"地图",但它们也不起作用。 谁能帮忙?
我假设您没有使用 # 作为注释(因为您必须使用//
(。
我得到的错误与您不同:
prog.cpp:24:1: error: ‘inFile’ was not declared in this scope
修复后,我没有收到编译错误。
顺便说一下,这段代码:
map <string, int> params; // errors
while ( paramFile.good() ){
getline(paramFile, line);
istringstream ss(line);
ss >> key >> value; // set the variables
params[key] = value; // input them into the map
}
可以改写为:
map <string, int> params; // errors
while ( paramFile >> key >> value ) {
params[key] = value; // input them into the map
}
在此代码段中,如果在尝试读取键和值后paramFile
良好,则( paramFile >> key >> value )
评估为 true。
struct kv_pair : public std::pair<std::string, std::string> {
friend std::istream& operator>>(std::istream& in, kv_pair& p) {
return in >> std::get<0>(p) >> std::get<1>(p);
}
};
int main() {
std::ifstream paramFile{"/home/bsxcto/Wedeman_NucPosSimulator/test/params.txt"};
std::map<std::string, std::string> params{std::istream_iterator<kv_pair>{paramFile},
std::istream_iterator<kv_pair>{}};
}
模板map
声明正确,问题出在注释中。#
不用作 C++ 中的一行注释//
.inFile.close();
更改为paramFile.close();
.
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 为什么不;名字在地图上是按顺序排列的吗
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- C++将文件内容读取到地图中
- C++,如何从文件中读取数据并插入容器:地图
- 从文件中读取数据并插入到地图C++中
- 如何从文件中读取输入并在C++中配对到地图中
- 将集合插入/读取到地图中
- 在 const 函数中从地图中未经选中读取
- 使用 valgrind 的地图中的读取大小错误无效
- 如何在使用 Boost C++ 编写的 php Web 应用程序中读取地图(在共享区域中)
- 如果我在键不存在的情况下读取地图的值,会发生什么情况?
- 房间地图游戏程序从文件读取
- 在yaml-cpp中读取地图
- 插入和读取值从3D地图
- std::在单独的线程中插入时读取地图