[英]How to read multiply char arrays from a file in C++
文件“ Athlete info.txt”如下所示:
Peter Gab 2653 Kenya 127
Usain Bolt 6534 Jamaica 128
Bla Bla 2973 Bangladesh -1
Some Name 5182 India 129
我希望我的代碼執行的操作是讀取第一個字符串並將其分配給firstName
數組(例如,將Peter存儲在firstName[0]
),讀取第二個字符串並將其分配給lastName
數組(例如,將Gab存儲在lastName[0]
)等等。我嘗試了許多不同的方法,甚至嘗試將其全部設置為字符串數組,但是它不起作用。 如果有人可以告訴我代碼中有什么問題或如何解決,那太好了!
提前致謝!
void readInputFromFile()
{
ifstream inputData;
inputData.open("Athlete info.txt");
const int SIZE=50;
char firstName[SIZE],
lastName[SIZE],
athleteNumber[SIZE],
country[SIZE];
int athleteTime[SIZE];
int numOfCharacters=0;
if (inputData.is_open())
{
int i=0;
while(!inputData.eof())
{
inputData >> firstName[i];
inputData >> lastName[i];
inputData >> athleteNumber[i];
inputData >> country[i];
inputData >> athleteTime[i];
i++;
numOfCharacters++;
}
for (int i=0; i < numOfCharacters; i++ )
{
cout << "First Name: " << firstName[i];
cout << "Last name: " << lastName[i];
cout << "AthleteNumber: " << athleteNumber[i];
cout << "Country: " << country[i];
cout << "Time taken: " << athleteTime[i];
cout << endl;
}
}
else
{
cout << "ERROR" << endl;
}
inputData.close();
}
首先,您正在使用c ++,所以讓我們使用std :: string並使用類。 讓我們創建一個運動員結構,其中包含運動員所需的一切:
struct Athlete {
Athlete() = default;
Athlete(std::stringstream &stream) {
stream >> firstName
>> lastName
>> athleteNumber
>> country
>> athleteTime;
}
// every Athlete is unique, copying should be prohibited
Athlete(const Athlete&) = delete;
std::string firstName;
std::string lastName;
std::string athleteNumber;
std::string country;
std::string athleteTime;
}
也許您可以多做一些工作並將其封裝得更好。
現在我們將使用std :: vector來存儲運動員,並且每次我們push_back時,都會使用輸入文件中的讀取行來調用Athelete構造函數。 稍后,您可以使用基於范圍的for循環來訪問vector中的每個運動員。 還要注意,如果不手動關閉ifstream,則一旦對象超出范圍,它將自動關閉。
void readInputFromFile() {
ifstream inputData("Athlete info.txt");
std::vector<Athlete> athletes;
std::string line;
std::stringstream ss;
if (inputData.is_open() {
while (getline(inputData, line)) {
ss.str(line);
// directly construct in-place
athletes.emplace_back(ss);
}
for (const Athlete& a : athletes) {
/* ...*/
}
} else {
std:cerr << "ERROR" << std::endl;
}
}
最簡單的更改是
while(inputData >> firstName[i])
{
inputData >> lastName[i];
inputData >> athleteNumber[i];
inputData >> country[i];
inputData >> athleteTime[i];
i++;
numOfCharacters++;
}
這將取決於輸入的格式正確。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.