簡體   English   中英

從文件C ++讀取特定值

[英]Reading specific values from file c++

我需要一些幫助來獲取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;
}

將您的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
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM