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;
}
+1 for忘記您編寫的所有內容,並使用C++。你怎麼能讓別人忘記? :) – FailedDev
@FailedDev:我希望我知道。我的基本規則是這樣的:「如果你使用指針,'新'或'使用名稱空間標準',你做錯了。」把它看作是值得的。我猜「帶有魔術常量的固定大小的數組」也應該放在那裏。 –
另外最好祿是我所見過的#define公私 - 這在產品代碼:) – FailedDev