【问题标题】:From file to variable? [closed]从文件到变量? [关闭]
【发布时间】:2013-08-21 17:37:10
【问题描述】:

我对 C++ 比较陌生,我想问一下如何“从文件中生成变量”。 我想编写一个程序来读取文件并使用符号作为标记, 就像一种分配语言。

我希望它发出这样的频率:

!frequency:time,frequency:time;//!=start/;=end

【问题讨论】:

  • 您能否提供一个输入文件的示例,以及您希望从中得到什么?
  • 你有没有先在google上搜索一下,看看this
  • 可能是std::map,使用std::string 键作为“变量符号”,而某种“变体”类型值容器可以满足您的需求。您应该使用示例输入和一些(伪)代码详细说明(编辑)您的问题,您打算如何使用这个。
  • 我希望它给出这样的频率:!frequency:time,frequency:time;//!=start/;=end

标签: c++ file variables io assign


【解决方案1】:

我是这样理解你的问题的。你有一个文件test.txt:

time      freq
0.001     12.3
0.002     12.5 
0.003     12.7
0.004     13.4 

然后你想读入这个文件,以便在一个容器中有time,在另一个容器中有freq,以便进一步处理。如果是这样,那么你的程序就是这样的:

#include<iostream>
using namespace std;

int main()
{
    ifstream in_file("test.txt");

    string label1, label2;
    float val;

    in_file >> label1;  //"time"
    in_file >> label2;   // "freq"

    vector<float> time;
    vector<float> freq;

    while (in_file >> val)
    {   
            time.pushback(val);
            in_file >> val;        
            freq.pushback(val);
    }   
 }

【讨论】:

  • 你有我可以照顾的一面吗?
  • @lixpoxx:here 是一个关于文件的 C++ 输入/输出的教程,如果这是你的意思
【解决方案2】:

针对我在评论中提到的内容提供更通用的解决方案:

#include <iostream>
#include <sstream>

int main()
{
    std::map<std::string, std::vector<double> > values_from_file;

    std::ifstream in_file("test.txt");


    std::string firstLine;
    std::getline(in_file, firstLine);
    std::istringstream firstLineInput(firstLine);

    // read all the labels (symbols)
    do
    {
        std::string label;
        firstLineInput >> label;
        values_from_file[label] = std::vector<double>();
    } while(firstLineInput);

    // Read all the values column wise
    typedef std::map<std::string, std::vector<double> >::iterator It;

    while(in_file)
    {
        for(It it = std::begin(values_from_file);
            it != std::end(values_from_file);
            ++it)
        {
            double val;
            if(in_file >> val)
            {   
                it->second.push_back(val);
            }   
        }
    }
}

【讨论】:

    猜你喜欢
    • 2017-12-21
    • 2018-11-30
    • 2015-05-29
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多