从文件c ++中读取特定值

时间:2012-01-26 08:55:25

标签: c++ file line fopen skip

我需要一些帮助来获取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;
}

1 个答案:

答案 0 :(得分:0)

像下面的代码一样放置你的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
    }