我正在为班级做一个项目,但我一直在单行上遇到同样的错误。我曾尝试向同学寻求帮助,但我无法让它发挥作用。从文件中读取数据时,程序应该将每一行转换为结构的信息,即动物的奇偶性、物种和数量。但是,每次在应该将最终缓冲区值从字符串转换为整数的行上,我都会收到一个无效的参数异常。这是我的代码。我已经用“ERROR OCCURS HERE!”标记了导致异常的行。
编辑:这是输入文件的内容。
Oviparous Spider 10
Oviparous Bird 5
Viviparous Snake 20
Viviparous Dog 5
end
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>
#include <sstream>
using namespace std;
struct animal {
string parity;
string species;
int count;
};
void displayMenu() { // Displays Menu.
cout << "------------------------\n";
cout << "--- MENU ---\n";
cout << "--- ---\n";
cout << "--- 1) Print Data ---\n";
cout << "--- 2) Add Animal ---\n";
cout << "--- 3) Display Menu ---\n";
cout << "--- 4) Quit ---\n";
cout << "--- ---\n";
cout << "------------------------" << endl;
}
int main()
{
// Initialises variables.
int choice;
string fullLine;
// Reads input file.
ifstream data("C:\\temp\\input.txt"); // Gets file.
if (data.is_open()) {
vector<animal> animals;
int lines = count( // Gets total lines.
istreambuf_iterator<char>(data),
istreambuf_iterator<char>(),'\n');
--lines; // One is subtracted because of the "end" line.
animals.resize(lines); // Resizes to total animals.
for (int i = 0; i < lines; i++) {
getline(data, fullLine); // Gets line.
istringstream buf(fullLine); // Splits line into parts.
buf >> animals[i].parity; // Assigns to parity.
buf >> animals[i].species; // Assigns to species.
string conversion; buf >> conversion; animals[i].count = stoi(conversion); // Assigns to count. ERROR OCCURS HERE!
}
// Menu loop.
displayMenu();
while (true) {
cin >> choice;
if (choice == 1) { // Prints data.
cout << "The zoo contains: \n";
for (int i = 0; i < lines; i++) {
cout << animals[i].count << " " << animals[i].species << ", which are " << animals[i].parity << ".\n";
}
}
else if (choice == 2) { // TODO: Adds animal.
}
else if (choice == 3) { // Displays menu.
displayMenu();
}
else if (choice == 4) { // Quits program.
break;
}
}
}
}