C++中的 getline() 函数不起作用

getline() function in C++ does not work

本文关键字:函数 不起作用 中的 getline C++      更新时间:2023-10-16

我在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";