【发布时间】: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++。