首页 > 解决方案 > 如何从文件中读取数字并将其用作 C++ 中的变量?

问题描述

假设我有一个正在阅读的文件,它是这样的:

#character         posX      posY //commentary line: explains what it represents
CharacterName1     50.0       0.0

CharacterName2     32.0       50.0

这里的目标是能够读取 posX et posY 并将它们在我的 C++ 程序中转换为 2 个双变量 x 和 y。

现在,我所能做的就是开始阅读文件并查看该行是否对应于空行或注释行。然后,如果阅读行找到相应的字符名称,我应该能够继续阅读这一行以获得 posX 和 posY,但我不知道如何做到这一点。我不知道如何跳过空白以及如何开始阅读数字以及如何完成阅读然后将其转换为双精度。

关于我应该如何做的任何想法?

我真的希望这足够清楚。

先感谢您。

尝试示例

void loadMap(std::string const& filepath) {


    std::ifstream infile(filepath.c_str());
    
    if(infile.fail()) {  
        
        std::cerr << "Error... " << std::endl;
        
    } else { /opening occured correctly
       
        while ( !infile.eof() ) {
            
            std::string line; 
            std::getline(infile, line);
            
            if ( (line[0] != '#') or (line.empty()) ) { //if line not comment or not empty
                  
                
                if( line.find("CharacterName1") ) {.......

然后我迷路了。

标签: c++fstreamiostream

解决方案


希望这段代码会有所帮助。

#include <bits/stdc++.h>
using namespace  std;         //change headers and namespaces; included for ease of use;

vector<string> split(const string &text, const char sep) {
    vector<string> tokens;
    std::size_t start = 0, end = 0;
    while ((end = text.find(sep, start)) not_eq string::npos) {
        tokens.emplace_back(text.substr(start, end - start));
        start = end + 1;
    }
    tokens.emplace_back(text.substr(start));
    return tokens;
}

    int main()
    {
       ofstream outdata;
       outdata.open("example.txt");
       if( not outdata ) {
          cerr << "Error: file could not be opened" << endl;
          exit(1);
       }
       outdata<<"CharacterName1"<<','<<10.0<<','<<40.0<<endl; //writing data into file
       outdata<<"CharacterName2"<<','<<20.0<<','<<30.0<<endl;
       outdata<<"CharacterName3"<<','<<30.0<<','<<20.0<<endl;
       outdata<<"CharacterName4"<<','<<40.0<<','<<10.0<<endl;
       outdata.close();

        ifstream inputFile;
        inputFile.open("example.txt",fstream::in);
        if (inputFile.fail())
        {
            cerr<<"Error: file could not be opened"<<endl;
            exit(1);
        }
        string line;
        vector<string> col1;
        vector<double> col2;
        vector<double> col3;
        while (getline(inputFile, line))
        {
            if(not line.empty()){

            auto lineData = split(line, ','); //separator can change in your case
            col1.emplace_back(lineData[0]);
            col2.emplace_back(std::stof(lineData[1]));
            col3.emplace_back(std::stof(lineData[2]));
            }
        }
        for(int i =0; i<(int) col1.size();i++)         //printing the data;
            cout<<col1[i]<<"\t"<<col2[i]<<"\t"<<col3[i]<<"\n";
       return 0;
    }

通过以下方式理解上述逻辑:

  1. 读取文件的每一行。

  2. 对于每一行,我们将通过函数将列数据分开,该split(string, sep)函数将返回vector<string>该行的包含数据。这sep是文件中使用的分隔符;当我将输入文件以逗号分隔时,我使用了','

  3. 将返回的vector<string>类型 row-data 转换为适当的数据类型并存储在相应的列向量col1, col2, col3中。

  4. split() 功能的参考

对于可能缺少一些数据的另一列,您可以添加一些逻辑,例如

if(lineData.size() > 3)
    col4.emplace_back(std::stof(lineData[3]));
else
    col4.emplace_back(0.0);

行后col3.emplace_back(std::stof(lineData[2]));


推荐阅读