我遇到的问题是我能够成功标记输入到我的函数parameters
的字符串menucall
,但是使用相同的方法我无法正确地标记从文件中获取的字符串getline
我不明白为什么。两个字符串都被正确分成了令牌。所有由字符串参数构成的标记都会删除其前导空格,而由字符串书制作的标记上的所有前导空格都不会。
Book和Bookstore是我创建的类。此后有更多代码,但它取决于这两个字符串的标记化。我的函数调用如下所示:
menuCall("1, BookInput.txt", store);
我的输入文件中的第一行如下所示:
12345, Michael Main, Data Structures, 100.00
void menuCall(string parameters, Bookstore bookstore)
{
ifstream in;
int i, o, option;
int j = 0, p = 0;
string optionToken, bookToken, book;
string *sp, *so;
Book newBook;
sp = new string[5];
so = new string[4];
while (parameters != "") //Check if the string is empty
{
i = parameters.find(",", 0); //Find next comma in the string
if (i > 0) //If a comma is found
{
optionToken = parameters.substr(0, i); //Substring ends at first comma
parameters.erase(0, i + 1); //Delete substring and comma from original string
while (optionToken[0] == ' ') //Check for spaces at beginning of token
{
optionToken.erase(0, 1); //Delete spaces at beginning of token
}
}
if (i < 0) //If no comma is found
{
optionToken = parameters; //Substring ends at the end of the original string
parameters.erase(0, i); //Delete substring from original string
while (optionToken[0] == ' ') //Check for spaces at beginning of token
{
optionToken.erase(0, 1); //Delete spaces at beginning of token
}
}
sp[j] = optionToken; //Token is added to dynamic array
j++; //Keeps track of iterations
}
option = stoi(sp[0]); //Change option number from string to usable int
switch (option) //Switch to determine what menu option is to be performed
{
case(1): //Case 1
in.open(sp[1]); //Open file from extracted token containing file name
while (!in.eof())
{
getline(in, book); //Get string containing book information from input file file
while (book != "") //Check if the string is empty
{
o = book.find(",", 0); //Find the next comma in the string
if (o > 0) //If a comma is found
{
bookToken = book.substr(0, o); //Substring ends at first comma
book.erase(0, o + 1); //Delete substring and comma from original string
while (bookToken[0] == ' ') //Check for spaces at beginning of token
{
bookToken.erase(0, 1); //Delete spaces at beginning of token
}
}
if (o < 0) //If no comma is found
{
bookToken = book; //Substring ends at the end of the original string
book.erase(0, o); //Delete substring from original string
while (bookToken[0] == ' ') //Check for spaces at beginning of token
{
bookToken.erase(0, 1); //Delete spaces at beginning of token
}
}
so[p] = bookToken; //Token is added to dynamic array
p++; //Keeps track of iterations
}
}
break;