[英]Outputting Data From A File Into Structs And Arrays Of Structs
我很難從文件中獲取數據並將其輸入到給定的結構和結構數組中,然后輸出文件。 我們提供了一個包含96行的文件,如下所示:
尼爾·阿爾津
2.3 6.0 5.0 6.7 7.8 5.6 8.9 7.6
巴貝奇,查爾斯
2.3 5.6 6.5 7.6 8.7 7.8 5.4 4.5
該文件將繼續供24個不同的人使用,然后以不同的分數重復(第二行)。 第一個數字(在這種情況下,兩個人均為2.3)是難度等級。 接下來的6個數字是分數。
我們得到此數據是為了設置結構和數組以及我的代碼:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cmath>
using namespace std;
int main ()
{
ifstream inFile;
inFile.open("C://diveData.txt");
// checking to see if file opens correctly
if (!inFile)
{
cout << "Error opening the file!" << endl;
}
const int numRounds = 2; // variable to hold the number of rounds
const int numScores = 7; // variable to hold the number of rounds
const int numDivers = 24; // variable to hold the number of divers
typedef double DifficultyList[numRounds]; // 1D array for storing difficulty of dives on each round
typedef double ScoreTable [numRounds] [numScores]; // 2D array of dive scores
// struct to store information for one diver
struct DiverRecord
{
string name;
double totalScore;
double diveTotal;
DifficultyList diff;
ScoreTable scores;
};
DiverRecord DiverList[numDivers];
// my attempt at printing out the contents of the file
while (!EOF)
{
for (int x = 0; x < 25; x++)
{
infile >> DiverList[x].name;
inFile >> DiverList[x].totalScore;
inFile >> DiverList[x].diveTotal;
cout << DiverList.[x].name << endl;
cout << DiverList.[x].totalScore << endl;
cout << DiverList.[x].diveTotal << endl;
}
}
return 0;
}
幾個問題:
ifstream
是否打開,使用ifstream::is_open
; end of file
,請嘗試下面的代碼; 如果我理解正確,則您的輸入文件格式應為:
名稱1,名稱2
難度評分1評分2 ...評分7
從這個意義上說, totalScore
不應從流中輸入,而應進行計算。
這是修訂版:
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;
struct DiverRecord
{
string a, b;
double totalScore;
double difficulty;
double scores[7];
};
int main ()
{
ifstream inFile("C://diveData.txt");
// checking to see if file opens correctly
if (!inFile.is_open()) {
cout << "Error opening the file!" << endl;
}
vector<DiverRecord> DiverList;
DiverRecord record;
char ch;
while (inFile) {
inFile >> record.a >> ch >> record.b >> record.difficulty;
record.totalScore = 0;
for (int i = 0; i < 7; ++i) {
inFile >> record.scores[i];
record.totalScore += record.scores[i];
}
DiverList.push_back(record);
}
// output your DiverList here.
return 0;
}
首先>>運算符以第一個空格字符結束輸入,因此當您讀取名稱時,您只會得到姓氏和逗號,它將嘗試將名字放入totalScore中。 要獲取全名,請執行以下操作。
string temp;
infile >> DiverList[x].name;
infile >> temp;
DiverList[x].name + " ";
DiverList[x].name + temp;
同樣,在輸出時,您不需要多余的“。”。
cout << DiverList[x].name << endl;
等等應該可以正常工作。
正如我在較早的評論中所說的那樣,我現在正集中精力於不使用結構和結構數組,而是嘗試使用其他功能來從文件中讀取數據。 我想以邏輯形式放置數據,例如:
人員姓名第一輪:難度分數第二輪:難度分數
但是我無法從文件訪問特定元素。
我使用的代碼是:
while(inFile)
{
string name;
getline(inFile, name);
cout << name << endl;
}
這將按原樣輸出數據文件,但是當我嘗試為難度和七個分數聲明不同的變量時,它根本無法正確輸出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.