如何在C++中从文件中读取数字并将其用作变量? [英] How to read a number from a file and use it as a variable in C++?

查看:137
本文介绍了如何在C++中从文件中读取数字并将其用作变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在阅读一个文件,该文件如下所示:

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

CharacterName2     32.0       50.0

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

目前,我所能做的就是开始阅读该文件,并查看该行对应的是空行还是注释行。 然后,如果阅读行找到相应的角色名称,我应该能够继续阅读此行以获得posX和posy,但我不知道如何做到这一点。我不知道如何跳过空格,如何开始读数字,以及如何读完数字然后将其转换为Double。

你知道我应该怎么做吗?

我真心希望这一点足够清楚。

提前谢谢您。

尝试示例

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") ) {.......

那我就迷路了。

推荐答案

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

#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]<<"	"<<col2[i]<<"	"<<col3[i]<<"
";
       return 0;
    }

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

  1. 阅读文件的每一行。

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

  3. 将返回的vector<string>类型的行数据转换为相应的数据类型,并存储在相应的列矢量col1, col2, col3中。

  4. reference拆分()功能。

对于可能缺少某些数据的另一列 您可以添加一些类似

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

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

这篇关于如何在C++中从文件中读取数字并将其用作变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆