从文件中获取产品总数
Get total products number from file
我有产品.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++的文本文件,可能对你有用。
相关文章:
- 获取文件数据预处理器宏
- 如何在Windows内核中获取文件大小
- 从 C 中的变量获取文件的路径,C++
- 如何使用 C/C++ 和 system() 系统调用以外的其他方法在 Linux 中获取文件功能?
- 如何使用 jpeglib.h 获取文件是否为 JPEG 类型
- 谁能告诉我,程序中的错误是什么?该程序仅用于获取文件扩展名
- 我需要通过窗口句柄(HWND)获取文件,我该怎么办?
- 如何用C++部分地获取文件中的行
- 使用内置的Windows方法获取文件夹的内容
- 在 Apache Velocity 模板语言中获取文件目录
- 如何在C#或C++中获取文件或文件夹的有效权限?有什么 API 吗?
- 对字符求和并减去以获取文件
- 从 FutureAccessList 同步获取文件夹路径
- 通过HTTPS从POCO StreamCopier获取文件下载进度
- 如何使用C 17获取文件大小
- getline 无法获取文件的第一行
- 如何使用 Win API 获取文件夹中的文件列表(带过滤器)
- 无法从零MQ ZMQ_SERVER套接字中获取文件描述符
- HttpQueryInfo 获取文件大小
- 通过文件资源管理器获取文件夹目录