【问题标题】:Reading specific values from file c++从文件 c++ 中读取特定值
【发布时间】:2012-01-26 08:55:25
【问题描述】:

我在获取 c++ 代码方面需要一些帮助,

情况是,我需要读取一个包含以下内容的文本文件:

//THIS LINE IS COMMENTED OUT
//THIS LINE TOO
Variable1 = "1"; //comment for this line
Address = "some text value here"; //comment for this line

所以现在我想使用 c++ 读取这个文本文件并将值检索为:

Variable1 = 1
Address = some text value here

那么我该如何完成这项工作,请需要您的专家帮助。 我只设法使用下面的代码跳过文本文件的注释行,但现在不知道如何读取变量。我是 C++ 新手

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
string line;
ifstream myfile ("text.txt");
if (myfile.is_open())
{
  while ( myfile.good() )
  {
    getline (myfile,line);
    if(line[0]=='/')
      continue;

    cout << line << endl;
  }
  myfile.close();
}

else cout << "Unable to open file";

return 0;
}

【问题讨论】:

  • 如何知道一行值的数据类型?有哪些可能的数据类型?您是否有指定文件格式(或任何其他规范)的语法?您希望如何在程序中存储和使用键/值对?
  • Ehm,你需要写一个C解析器吗?从头开始?这是很多工作。顺便说一句,您当前的代码并不好,因为它会丢失像 /*comment*/ var = 1; 这样的行中的变量
  • 查看std::stringfindsubstr 函数。它们可用于将字符串拆分为您需要的名称/值对。然后使用std::map 来存储值。

标签: c++ file line fopen skip


【解决方案1】:

像下面的代码那样放置你的 while 循环。这肯定会奏效...

while ( myfile.good() )
{
    getline (myfile,line);
    while(line[i]!="\n" || line[i]!='\0')
    { 
        int i=0;

        // we have to check that there is continuously two '/' operator 
        if(line[i]=='/' && line[i+1] == '/')
        {
            while(line[i]!="\n" || line[i]!='\0') // this loop will jump next to comment
                i++;
            break; // this break is used to break the upper one while loop 
        }
        else    
            cout << line[i] << endl; // this line print all character that is before the comment
    }

【讨论】:

  • 你测试过这段代码吗?因为里面有错误,肯定不行。
  • 是的,我已经使用了它.. 它会在我的项目中... @BjörnPollex
  • @BjörnPollex - txt 文件的格式将是,首先到行 cmets.. 然后是下一行,变量后跟值,然后是该行的可选注释
猜你喜欢
  • 2015-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-13
  • 2017-06-08
相关资源
最近更新 更多