2017-04-12 56 views
-1

我有一段代碼,我試圖學習如何在C++中解析。我明白了我所做的一切,但我不明白如何使用atoi(),atof(),strtod()。我知道它應該做什麼,但我不明白爲什麼編譯器不喜歡它。我關注錯誤的是「scores [line_count] = strtod(score);」如何使轉換功能起作用?

#include <iostream> 
#include <fstream> 
#include <string> 
#include <stdlib.h> 
#include <iomanip> 

using namespace std; 

int readScores(string inputFile, string name[], float scores[], int  array_size) 
{ 
//delcare variables 
ifstream infile; 
int line_count = 0; 
string line; 
string named; 
float score; 
char character; 
int word_index; 
string names[array_size]; 


// open input file 
infile.open(inputFile); 

//Check if file opens succesfully. 
if(infile.fail()) 
{ 
    cout << "File cannot open!!" << endl; 
    return -1; 
} 

while(getline(infile, line)) 
{ 
    cout << line << endl; 
    // PARSING GOES HERE 

    word_index = 0; 

    for(int i=0; i < (int)line.length(); i++) 
    { 
     character = line[i]; 

     if (character == ',') 
     { 
      names[line_count] = named; 
      named = ""; 
      word_index++; 
     } 
     else 
     { 
      if(word_index == 0) 
      { 
       named += character; 

      } 
      else if (word_index == 1) 
      { 
       score += character; 
       cout << character << " " << endl; 
      } 
     } 

    } 
scores[line_count] = strtod (score); 



    line_count++; 

} 

//close file 
infile.close(); 

//return line count 
return line_count; 
cout << line_count << endl; 
} 

int main(void) 
{ 
int array_size = 50; 
string inputFile = "Test.txt"; 
string name [array_size]; 
float scores [array_size]; 


readScores(inputFile, name, scores, array_size); 
} 
+0

「編譯器不喜歡它」不是一個非常有用的描述。 – John3136

+0

它給了我一個錯誤。它說,「不能將const char *轉換爲參數1。」 – Robbie

+0

@Robbie爲什麼它沒有幫助?你傳遞'float'而不是'char *'! –

回答

0

功能的strtod()的形式爲

double strtod (const char* str, char** endptr); 

但你只給它的字符串。

正如你所看到的,它需要兩個參數,你希望轉換成double的字符串和一個「endptr」。所述endptr描述here作爲

參考類型char *的已分配的對象,其值由>該函數的數值後設置爲下一個字符在str中。 該參數也可以是一個空指針,在這種情況下它不被使用。

因此,您需要聲明一個字符指針來保存小數點後的下一個字符,即使不會是一個字符。這允許你從單個字符串中拉出多個雙打,就像一個分詞器。

char * endPtr; 
scores[line_count] = strtod(score, &endPtr); 

編輯

亞歷克斯羅布泊指出的那樣,你甚至不傳遞一個字符串的strtod,你傳遞一個浮動。看起來你想將浮點數轉換爲double?

+0

好吧......說我把它改成atof(得分)......我仍然得到同樣的錯誤。 double afof(const char * _nptr) – Robbie

+1

這是因爲atof()將一個字符串轉換爲一個float,並且您仍然會將其傳遞給一個float。我的建議是在使用它們之前查看功能的手冊頁,以便您確切知道它們的功能以及需要傳遞的參數。 – rhysvo

0

當然編譯器不喜歡它。請閱讀strtod的描述。

double strtod(const char * str,char ** endptr);

string轉換成 double

解析C-串str解釋其內容作爲浮動 點數目(根據當前環境),並返回它的值 作爲double。如果endptr不是null指針,該函數還會將 的值設置爲endptr以指向數字後面的第一個字符。

函數首先根據需要丟棄儘可能多的空白字符(如 isspace),直到找到第一個非空白字符爲 。然後,從這個字符開始,採用與 一樣多的字符,這些字符在類似浮點數的文字(參見下文)後可能是有效的,並將它們解釋爲數字值。 指向endptr指向的對象中最後一個有效字符後面的字符串其餘部分的指針爲 。

並在代碼中傳遞給strtod只有一個參數是float型和double返回結果存儲到的float秒的陣列。如果你想的float值從一個變量移動到另一個,你不需要任何「皈依」的功能:

scores[line_count] = score; 

注:我真的不檢查代碼,爲您專門問scores[line_count] = strtod (score);。但在我看了你如何修改score後,也許它應該是string而不是float。如果是這樣,那麼這是另一個需要解決的問題。