C++将文件内容读取到地图中

C++ reading contents from file into a map

本文关键字:地图 读取 文件 C++      更新时间:2023-10-16

我有一个文件,我想读入地图。

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();.