从文件中获取产品总数

Get total products number from file

本文关键字:获取 文件      更新时间:2023-10-16

我有产品.txt文件:

Chocolate Milka 5 250
Soda Fanta 3 2
... 

如您所见,数据按顺序输入:名称、制造商、价格、数量。我需要编写一个程序来确定产品.txt文件中有多少产品。

我尝试过:

int number_of_lines = 0;
std::string line;
while (std::getline(myfile, line))
++number_of_lines;
std::cout << "Number of lines in text file: " << number_of_lines;

但结果它抛出 0。我尝试使用文件中的行数来确定产品总数,因为行数 = 产品数?

代码有效,如注释中所示,您可能由于某种原因(错误的路径、读取权限等(无法打开文件。

尝试添加 if 以检查文件是否正确打开,如下所示

#include <fstream>
#include <iostream>
int main(int argc, char *argv[]) {
std::ifstream myfile;
myfile.open("products.txt");
if (myfile) {
int number_of_lines = 0;
std::string line;
while (std::getline(myfile, line))
++number_of_lines;
std::cout << "Number of lines in text file: " << number_of_lines;
} else {
std::cout << "Could not open the file" << std::endl;
}
return 0;
}

但请注意,此代码计算的是文件中的行数,而不是产品数。因此,任何空行都将计为产品。

这个答案有一种非常好的方法来读取和解析C++的文本文件,可能对你有用。