【问题标题】:How to read a number from a file and use it as a variable in C++?如何从文件中读取数字并将其用作 C++ 中的变量?
【发布时间】:2021-08-13 11:32:03
【问题描述】:

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

#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++ fstream iostream


【解决方案1】:

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

#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&lt;string&gt;。这里sep是文件中使用的分隔符;当我使用逗号分隔输入文件时,我使用了','

  3. 将返回的vector&lt;string&gt;类型行数据转换为适当的数据类型并存储在相应的列向量col1, col2, col3中。

  4. reference 的 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])); 行之后。

【讨论】:

  • 您可能花了一些时间才写出来。为什么不用充分的解释来完成答案?我也会删除前两行 - 你不会经常在生产代码中看到它们。
  • 我从没见过有人不讽刺地使用not_eq。你真的认为这比!=更易读吗?
  • @Bathsheba 我正在等待帖子所有者确认它是否是必需的解决方案,以便我可以提供更好的解释。
  • @Bathsheba 一定帮帮我?
  • @dixit_chandra:谢谢。反对票转换为赞成票!
猜你喜欢
  • 2022-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-27
  • 1970-01-01
  • 2019-12-22
  • 1970-01-01
相关资源
最近更新 更多