如何从文本文件中的某些行开始读取
C++: how to start reading from certain lines in a txt file?
c++初学者项目,帮助程序从某些行开始读取。
我们有一个输入文本文件,其中包含一些客户信息:姓名、地址、两个数字,每个部分占一行。我们需要读取文件,打印出名称、地址,对数字进行一些计算,并将所有三个输出发送到输出文件。
文本文件包含3个case(9行)。
我可以读取一个案例,但是我在编写一个可以遍历三个案例的循环时遇到了麻烦。我怎样才能告诉c++,它需要从第四行开始,并做与第一个情况相同的迭代?下面是我对第一种情况所做的处理。
getline(infile, customerName);
getline(infile, customerAddress);
infile >> sqFeetOfTile >> costPerSqFt;
听起来好像您实际上并不想从第4行开始阅读(跳过3行),而是想要阅读3行,然后在第4行继续。
在这种情况下,你唯一的问题是读取数字不消耗它们后面的换行符,所以当你在那之后getline
时,唯一的换行符成为第一个"行",不久之后,当你试图将地址读到sqFeetOfTile
时,你会遇到一个错误。
最好的方法是始终读取完整的行。
如果一行包含多个部分,则将其转换为std::istringstream
并从中读取部分。
这个方法不会在流中留下任何多余的换行符,你可以从第一个记录结束的地方继续。
:
void processOneCustomer(std::istream& infile)
{
std::string customerName;
std::getline(infile, customerName);
std::string customerAddress;
std::getline(infile, customerAddress);
std::string numbers;
std::getline(infile, numbers);
std::istringstream numberstream(numbers);
float sqFeetOfTile = 0;
int costPerSqFeet = 0;
numbers >> sqFeetOfTile >> costPerSqFt;
// Output customer data
// Do calculations
}
// ...
while (inFile)
{
processOneCustomer(inFile);
}
(当然,真正的代码应该检查错误之类的东西。)
如果您想跳过前三行,只需调用std::getline
三次。
相关文章:
- 使 std::fstream 写入文件末尾,但从头开始读取
- 如何继续读取不同功能中的文件,而不是从头开始再次读取文件?
- 停止和开始读取/复制二进制文件
- 将文本文件读取到2D数组中,但数组开始为超过数组[39][]的任何内容输出胡言乱语
- 设置从文件中读取的开始和结束限制
- 读取从ifstream中n的位置n开始的二进制字节
- 常时等量启动失败.错误: 0x2 ;当开始从 2 个相机 PTGrey 读取时
- 为什么C++向量大小从 4294967296 开始,而调试器将其读取为 0?
- 从特定行开始将文件读取到对向量中
- C I2C芯片读取MCP9800突然开始失败
- 从第 3 位开始读取 int 的最快方法?
- 从.txt文件MFC C++的特定行开始读取
- 如何读取从特定索引开始的字符串
- 为什么开始读取返回错误ENOMEM(_B)
- C++ 使用 while 循环读取文件,从第 "x" 行开始
- C++ 使用开始和结束读取文件的特定部分
- 从包含特定字符串的行开始读取
- 从链表的末尾开始读取值,而不是从开头
- 如何开始读取文件中文本的某些部分,一旦找到文本之前的关键字
- 如何从文本文件中的某些行开始读取