【问题标题】:getline() function in C++ does not workC++ 中的 getline() 函数不起作用
【发布时间】:2013-01-30 12:35:01
【问题描述】:

我用 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 .

【问题讨论】:

  • 我们需要“while (!file.eof()) 错了!”永久固定在 Stack Overflow 的顶部。
  • @sftrabbit 是的。问题是有些网站在他们的示例中使用它,并声称了解 C++。

标签: c++ file getline


【解决方案1】:
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 的答案。

【讨论】:

  • 对不起,这是我的错误,是的,我已经在使用 ios::beg 但它仍然无法正常工作。
  • 不知道file.clear(),问题已解决,谢谢。
【解决方案2】:

您的代码正在犯各种错误。您从不检查任何错误状态!

应该是这样的:

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

【讨论】:

    猜你喜欢
    • 2019-08-09
    • 2013-10-15
    • 1970-01-01
    • 1970-01-01
    • 2013-09-10
    • 2014-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多