I need to parse the following file so it takes the item as a string then skip the # sign and then take the price as a float. text file:
hammer#9.95
saw#20.15
shovel#35.40
how would I go about doing this?
将文件逐行读入字符串。查找#
第二部分并将其解析为浮点数。
std::ifstream file("input.txt");
for (std::string line; std::getline(file, line); )
{
auto sharp = line.find('#'); // std::size_t sharp = ...
if (sharp != std::string::npos)
{
std::string name(line, 0, sharp);
line.erase(0, sharp+1);
float price = std::stof(line);
std::cout << name << " " << price << "\n";
}
}
注意:我没有做一些错误检查,作为练习自己做。你也应该知道std::string
,std::ifstream
和.std::getline
std::stof
如果你有 std::string 呈现格式,你可以使用这样的东西:
std::string test {"test#5.23"};
std::cout << std::stof(std::string{test.begin() + test.rfind('#') + 1, test.end()});
注意 std::stof 是 C++11 函数