簡體   English   中英

從txt文件中讀取雙精度類型-C ++

[英]Read in double type from txt file - C++

我正在參加一個大學項目,因此決定實現一種方法,該方法可以接受來自文本文件的信息(在本例中為“ locations.txt”)。 來自文本文件的輸入將如下所示:

London
345
456
Madrid
234
345
Beinjing
345
456
Frankfurt
456
567

該函數當前看起來像這樣(您會注意到,當我到達locations.txt中的文本結尾時,我缺少While條件來完成添加輸入的操作,我嘗試使用eof,但這沒用嗎?!)。 同樣get函數期望一個char字符,因此不能接受多數民眾贊成在兩倍,這是經度和緯度定義為...

void populateList(){
  ifstream inputFile;
  inputFile.open ("locations.txt");
  temp  = new locationNode; // declare the space for a pointer item and assign a temporary pointer to it


  while(HASNT REACHED END OF TEXT FILE!!)
  {
     inputFile.getline(temp->nodeCityName, MAX_LENGTH);
     // inputFile.get(temp->nodeLati, MAX_LENGTH);
     // inputFile.get(temp->nodeLongi, MAX_LENGTH);

     temp->Next = NULL; //set to NULL as when one is added it is currently the last in the list and so can not point to the next

     if(start_ptr == NULL){ // if list is currently empty, start_ptr will point to this node

        start_ptr = temp;
     }

     else {
        temp2 = start_ptr;
        // We know this is not NULL - list not empty!
        while (temp2->Next != NULL)
           {  
            temp2 = temp2->Next; // Move to next link in chain until reach end of list
           }

        temp2->Next = temp;
     }
  }
  inputFile.close();
}

您可以提供的任何幫助將是最有用的。 如果我需要提供更多細節,我將在繁忙的食堂自動取款機中,而且專心致志!!

std::string city;
double lat, lgt;

while( (inputFile >> city ) &&  (inputFile >> lat) && (inputFile >> lgt ) )   {
    // do something with values
}

您可以將getline()調用作為while循環的條件。 一旦達到EOF,其返回值將評估為false。

getline()很重要,因為類似於cin >> str; 只會讀取城市名稱的首字母,例如“紐約”或“胡志明市”。 如Kristo建議的那樣,將其置於while循環條件中。

之后,您有兩種可能。 您可以使用標准流來讀取雙倍,在這種情況下,應確保您正在讀取所有適當的換行符。 file >> double_var;下面的換行符進行讀取,因此下面的getline()將獲得該行的其余部分,該行為空,而不是下一行。)當您確定輸入內容時,這種方法就可以工作格式正確,在作業問題中比在現實世界中普遍得多。

或者,您可以使用getline()讀取每一行,然后將文本轉換為自己的兩倍。 當然,有不同的方法。 C函數atod()最簡單,但如果數字為0或不是數字,則將返回0。 C函數strtod()設置更為復雜,但可以區分這兩種情況。 您可以使用C ++解決方案istringstream ,但是在這種情況下,看起來麻煩多於其所值。

您可以使用fstream然后執行:

double d;
fs>>d;

我認為您錯過了eof的NOT。 它應該看起來像這樣:

while( !File.eof() ); //eof is set when reached end of file.
// and you are looking for while NOT reached end of file..

暫無
暫無

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

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