2011-04-29 83 views
1

當前正在處理片段以輸入用戶更改稍後使用的文本文件的變量。將它們存儲在一個數組中,稍後將它們引用到一些openGL中。爲C++中的雙變量輸入解析.txt文件

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

東西= 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(); 

現在它是保存所有的數值數組中的初始化,但不得遲覆蓋它們,因爲當我行闖入令牌它應該。任何幫助表示讚賞。

+0

爲什麼iostream和C風格的IO的隨機混合? – genpfault 2011-04-29 18:32:57

+3

這不能解決你的問題,但你爲什麼要混合使用C++和C風格的字符串?首先,你已經設計了一個內存泄漏(內存指向'buf'的地方?)。 – 2011-04-29 18:33:18

+0

我看到,但是要使用strtok我必須創建buf轉換爲字符串中的字符。不知道有任何其他方式來解決這個問題。還有其他解決問題的想法? – Kyle 2011-04-29 18:50:42

回答

0

要申請什麼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()); 
} 
1

它看起來對我來說,錯誤是在這裏:

N [1] =的strtod(strtok的(BUF, 「;」),NULL);

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

然後strtod()會嘗試將其轉換爲double,但字符串「something = 18.0」不會輕易轉換爲double。你需要首先標記初始的「something =」,並在必要時丟棄這些數據(或者如果你願意,可以用它做些什麼)。

您可能希望參考此主題以獲取更多C++的想法 - 風格的方式來標記你的字符串,而不是C風格像你目前正在使用:

How do I tokenize a string in C++?

好運!