我正在尝试制作一个小型图书馆系统,用户可以在其中添加新书的详细信息(名称、作者和价格)。当实现 FileIO 系统以使用 getline 函数从文件中读取每本书的详细信息时,当我尝试将变量存储在临时变量中时,将它们分开变得更加困难。
例如:
“No 是一个四个字母的单词,Chris Jericho,17.67,”
“哈利波特,JK 罗琳,23.98,”
PS:有没有比加逗号更好的解决办法?
我尝试添加一个“,”字符来分隔我的每个字符串,但我需要一个更好、更高效的解决方案来与 getLine 函数一起使用。
int main(){
vector<Book> library;
//----Loading File Data_START
string line;
int nbArg=0;
string tempName, tempAuthor, tempPrice;
ifstream myfileL("List.txt");
if (myfileL.is_open())
{
while (getline(myfileL, line))
{
tempPrice=tempAuthor = tempName = "";
for (int j = 0; j < line.size(); j++){
if (line.at(j) == ','){
nbArg++;
}
else{
switch (nbArg){
case 0:
tempName += (line.at(j));
break;
case 1:
tempPrice += (line.at(j));
break;
case 2:
tempAuthor += (line.at(j));
break;
}
}
}
cout << tempName << endl << tempAuthor << endl << tempPrice << endl;
cout << "End of Line"<< endl;
nbArg = 0;
}
cout << "---------------------------" << endl;
myfileL.close();
}
else cout << "Unable to open file";
//----Loading File Data_END
char inputKey = 's';
cout << "-----------------WELCOME----------------" << endl;
while (inputKey != 'q')
{
cout << "---------------------------------------" << endl;
cout << "Click \"1\" to add a book to your library" << endl;
cout << "Click \"2\" to show how the number of books your possess" << endl;
cout << "Click \"3\" to show details about your books" << endl;
cout << "Click \"q\" to quit" << endl;
cin >> inputKey;
switch (inputKey)
{
case '1':
addElem(library);
break;
case '2':
cout << "You now own " << libSize(library) << " books !" << endl;
break;
case '3':
showDetails(library);
break;
case 'q':
cout << "GOODBYE!" << endl;
Sleep(2000);
break;
}
}
return 0;
最佳答案
使用专门的文件格式,可以包含结构(例如 json、xml)。这将避免很多很多问题。
如果不能,则添加一个分隔符(就像您所做的那样),但选择一个在实际字符串中出现的机会最少的字符。因此,例如行尾(每个变量都在其自己的行上)或\0 或\t。
关于C++ FileIO 读取和写入对象变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55762662/