2011-12-03 64 views
1

我需要從一個文本文件中讀取數據,並在結構數組插入數據的數組。數據文件是按以下格式:如何插入從文本文件數據到結構

productname price quantity 

我主要關注的是閱讀產品的名稱,它由一,兩個單詞。我應該將產品名稱視爲c字符串還是字符串字面值?

任何幫助讚賞

#include <iostream> 
#include <fstream> 

using namespace std; 

const int SIZE = 15; //drink name char size 
const int ITEMS = 5; //number of products 

struct drinks 
{ 
     char drinkName[SIZE]; 
     float drinkPrice; 
     int drinkQuantity; 
};  


int main() 
{ 
    //array to store drinks 
    drinks softDrinks[ITEMS]; 

    //opening file 
    ifstream inFile; 
    inFile.open("drinks.txt"); 

    char ch; 
    int count = 0; //while loop counter 


    if(inFile) 
    { 
     while(inFile.get(ch)) 
     { 
      //if(isalpha(ch)) { softDrinks[count].drinkName += ch; } 
      //if(isdigit(ch)) { softDrinks[count].drinkPrice += ch; } 
      cout << ch; 

     } 
     cout << endl; 
     count++; 
    } 
    else 
    { 
     cout << "Error opening file!\n"; 
     system("pause"); 
     exit(0); 
    } 

    system("pause"); 
    return 0; 
} 

回答

3

既然你問到了「任何幫助」,這是我的觀點:忘記你寫的一切,並使用C++:

#include <fstream> // for std::ifstream 
#include <sstream> // for std::istringstream 
#include <string> // for std::string and std::getline 

int main() 
{ 
    std::ifstream infile("thefile.txt"); 
    std::string line; 

    while (std::getline(infile, line)) 
    { 
     std::istringstream iss(line); 

     std::string name; 
     double price; 
     int qty; 

     if (iss >> name >> price >> qty) 
     { 
      std::cout << "Product '" << name << "': " << qty << " units, " << price << " each.\n"; 
     } 
     else 
     { 
      // error processing that line 
     } 
    } 
} 

你可以存儲數據的每一行例如,在std::tuple<std::string, int, double>中,然後將這些放入std::vector中。

+1

+1 for忘記您編寫的所有內容,並使用C++。你怎麼能讓別人忘記? :) – FailedDev

+1

@FailedDev:我希望我知道。我的基本規則是這樣的:「如果你使用指針,'新'或'使用名稱空間標準',你做錯了。」把它看作是值得的。我猜「帶有魔術常量的固定大小的數組」也應該放在那裏。 –

+1

另外最好祿是我所見過的#define公私 - 這在產品代碼:) – FailedDev

相關問題