使用分隔符从文件分配变量

时间:2019-03-05 20:16:22

标签: c++ boost ifstream

我有一个文件map.txt:

Montreal|Quebec,Toronto|30,40
New York|Boston,Philadelphia,Scranton|20,10,50

我要在“ |”之前分配第一部分到cityString,第二部分到edgeString,第三部分到costString。然后,我将使用boost将字符串拆分为相应的向量,并将这些向量分配给自定义的CityNode对象。

这是我的代码:

string cityString;
string edgesString;
string costString;
vector<string> edgesVector;
vector<string> costVector;
vector<CityNode> cities;
int i = 0;
bool used = true;
string line;
ifstream myfile(this->fileName);

if (myfile.is_open())
{
    while (getline(myfile, line))
    {
        cout << cityString << "|" << edgesString << "|" << costString << "\n";    // read line of file

        boost::split(edgesVector, edgesString, [](char c) {return c == ','; });    //split edgesString into vector delimiter: ','
        boost::split(costVector, costString, [](char c) {return c == ','; });    // split costString into vector delimiter: ','


        //ASSIGN VARIABLES
        cities[i].setValues(cityString, edgesVector, costVector);
        i++;
    }

    myfile.close();
}
else cout << "Incorrect file format";
return cities;

当我打电话

 cout << cities[0].getName();

我知道

||
||

代替我想要的“蒙特利尔”。我认为错误是我从文件中读取变量的方式,但我不知道如何解决。请帮忙。

2 个答案:

答案 0 :(得分:0)

请尝试以下类似操作:

string edgesString;
string costString;
string line;
vector<string> edgesVector;
vector<string> costVector;
vector<CityNode> cities;

ifstream myfile(this->fileName);
if (myfile.is_open())
{
    while (getline(myfile, line))
    {
        istringstream iss(line);
        getline(iss, cityString, "|");
        getline(iss, edgesString, "|");
        getline(iss, costString);

        cout << cityString << "|" << edgesString << "|" << costString << "\n"; // display line from file

        auto onComma = [](char c){ return c == ','; };
        boost::split(edgesVector, edgesString, onComma); //split edgesString into vector delimiter: ','
        boost::split(costVector, costString, onComma); // split costString into vector delimiter: ','

        //ASSIGN VARIABLES
        CityNode city;
        city.setValues(cityString, edgesVector, costVector);
        cities.push_back(city);
    }

    myfile.close();
}
else
    cout << "Cannot open file";

return cities;

答案 1 :(得分:-1)

据我了解,这里有很多事情: 首先,文件的实际内容存储在line变量中。 此变量似乎永远不会使用。因此,您的向量没有设置。

然后,控制台上的输出是'cout << cityString <<“ |”的结果<< edgesString <<“ |” << costString <<“ \ n”;`语句,因为您从不会影响这些变量的任何值,所以它们是“空字符串”。而且由于文件中有2行,而while语句则以:

结尾
||
||

我还认为您可以在不使用Boost的情况下进行拆分。

使用此代码,您将获得正确的输出:

boost::split(lineVect, line,[](char c) { return c == '|'; });

cout << lineVect[0] << "|" << lineVect[1] << "|" << lineVect[2] << "\n";    

boost::split(edgesVector, lineVect[1], [](char c) { return c == ','; });    //split edgesString into vector delimiter: ','
boost::split(costVector, lineVect[2], [](char c) { return c == ','; });    // split costString into vector delimiter: ','

//ASSIGN VARIABLES
cities[i].setValues(lineVect[0], edgesVector, costVector);
i++;