簡體   English   中英

C++ 中雙變量輸入的 Parsing.txt 文件

[英]Parsing .txt file for double variable input in C++

目前正在處理一個片段以輸入變量,其中用戶更改了稍后使用的文本文件。 將這些存儲在一個數組中,然后在某些 openGL 中引用它們。

輸入文本文件看起來像這樣。

某事= 18.0;

別的東西= 23.4;

... 共 6 行

//the variable of type ifstream:
ifstream patientInput(".../Patient1.txt");
double n[6]= {0.0,0.0,0.0,0.0,0.0,0.0};
register int i=0;
string line;
//check to see if the file is opened:
 if (patientInput) printf("Patient File Successfully Opened.\n");

else printf("Unable to open patient file\n");

 while(!patientInput.eof())
 {
    getline(patientInput,line);
    char *ptr, *buf;
    buf = new char[line.size() + 1];
    strcpy(buf, line.c_str());
    n[i]=strtod(strtok(buf, ";"), NULL);
    printf("%f\n",n[i]);
    i++;
 }
//close the stream:
patientInput.close();

現在它將數組中的所有值保存為已初始化但以后不會覆蓋它們,就像我將行分成標記時那樣。 任何幫助表示贊賞。

在我看來,這個錯誤就在這里:

n[i]=strtod(strtok(buf, ";"), NULL);

在第一次運行 while 循環時,strtok() 將返回 C 字符串,例如“something = 18.0”。

然后 strtod() 將嘗試將其轉換為雙精度,但字符串“something = 18.0”並不那么容易轉換為雙精度。 您需要首先標記初始的“something =”,並在必要時丟棄該數據(或者如果您願意,可以對其進行處理)。

您可能需要參考此線程以獲得更多 C++ 樣式的字符串標記方法的想法,而不是您當前使用的 C 樣式:

如何標記 C++ 中的字符串?

祝你好運!

要應用 NattyBumppo 所說的,只需更改:

n[i]=strtod(strtok(buf, ";"), NULL);

至:

strtok(buf," =");
n[i] = strtod(strtok(NULL, " ;"), NULL);
delete buf;

當然,沒有 strtok 的情況下還有很多其他方法可以做到這一點。

這是一個例子:

ifstream input;
input.open("temp.txt", ios::in);
if( !input.good() )
    cout << "input not opened successfully";

while( !input.eof() )
{
    double n = -1;
    while( input.get() != '=' && !input.eof() );

    input >> n;
    if( input.good() )
        cout << n << endl;
    else
        input.clear();

    while( input.get() != '\n' && !input.eof() );
}

暫無
暫無

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

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