0

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

1 回答 1

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
    }
于 2012-01-26T10:02:56.110 回答