C++中的 getline() 函数不起作用
getline() function in C++ does not work
我在C++中写了一个代码,它打开一个.txt文件并读取其内容,将其视为(MAC地址数据库),每个MAC地址都由(.)分隔,我的问题是在我搜索文件的总行数后,我无法返回指向文件的初始位置的指针,我在这里使用seekg() and tellg()
来操作指向文件的指针。
这是代码:
#include <iostream>
#include <fstream>
#include <conio.h>
using namespace std;
int main ()
{
int i = 0;
string str1;
ifstream file;
file.open ("C:\Users\...\Desktop\MAC.txt");
//this section calculates the no. of lines
while (!file.eof() )
{
getline (file,str1);
for (int z =0 ; z<=15; z++)
if (str1[z] == '.')
i++;
}
file.seekg(0,ios::beg);
getline(file,str2);
cout << "the number of lines are " << i << endl;
cout << str2 << endl;
file.close();
getchar();
return 0;
}
以下是 MAC.txt 文件的内容:
0090-D0F5-723A.
0090-D0F2-87HF.
B048-7AAE-T5T5.
000e-f4e1-xxx2.
1C1D-678C-9DB3.
0090-d0db-f923.
D85D-4CD3-A238。
1C1D-678C-235D.
here the the output of the code is supposed to be the first MAC address but it returns the last one .
file.seekg(0,ios::end);
我相信你想在这里file.seekg(0,ios::beg);
。
从末尾的零偏移量(ios::end
)是文件的结尾。读取失败,只剩下缓冲区中读取的最后一个值。
另外,一旦你到达 eof
,你应该在寻求之前用file.clear();
手动重置它:
file.clear();
file.seekg(0,ios::beg);
getline(file,str2);
如果在执行文件操作时检查错误,则更容易捕获错误。有关示例,请参阅Kerrek SB的答案。
你的代码犯了各种各样的错误。您从不检查任何错误状态!
这是它应该的方式:
std::ifstream file("C:\Users\...\Desktop\MAC.txt");
for (std::string line; std::getline(file, line); )
// the loop exits when "file" is in an error state
{
/* whatever condition */ i++;
}
file.clear(); // reset error state
file.seekg(0, std::ios::beg); // rewind
std::string firstline;
if (!(std::getline(file, firstline)) { /* error */ }
std::cout << "The first line is: " << firstline << "n";
相关文章:
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- 为什么我的数组双精度函数不起作用?
- std::函数不起作用,但普通的旧函数指针可以 - 为什么?
- C++ Arduino - 随机函数不起作用
- 为什么我的数组或函数不起作用?
- 从类中的另一个文件请求函数不起作用
- 双链表堆栈删除函数不起作用
- 将 cmake 代码段转换为函数 - 不起作用
- 为什么我的从base64解码的函数不起作用?
- 为什么当我们使用等于'='符号比较器函数时,c ++的内置排序函数不起作用?
- swap(int&, int&) 函数不起作用,当交换不使用临时变量时?
- 子类化 STL 容器:范围构造函数不起作用
- 带有此指针的模板类多重继承构造函数不起作用?
- 以下打印树函数不起作用为什么?
- 为什么内存集函数不起作用?
- 调用填充我的主体数组的函数不起作用
- 带有自定义数字的阶乘函数不起作用
- 如何QDialog raise()函数不起作用
- Lambda 表达式闭包函数不起作用
- C++:在没有 lvalue 的情况下调用时复制构造函数不起作用