gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:23:42 26 4
gpt4 key购买 nike

我用 C++ 编写了一段代码,它打开一个 .txt 文件并读取其内容,将其视为一个(MAC 地址数据库),每个 mac 地址由(.)分隔,我的问题是在我搜索文件的总行数,我无法返回指向文件初始位置的指针,我在这里使用 seekg() 和 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。

此处代码的输出应该是第一个 MAC 地址,但它返回最后一个。

最佳答案

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 的回答。

关于c++ - C++ 中的 getline() 函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14604141/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com