1

私はC++でコードを書き、.txtファイルを開いてその内容を読み取り、それを(MACアドレスデータベース)と考えます。各MACアドレスは(。)で区切られています。問題は、ファイルで合計を検索した後です。行数、iamはポインタをファイルの初期位置に戻すことができません。ここでは、ファイル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 .

4

2 に答える 2

3
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);

ファイル操作を実行するときにエラーをチェックした場合、エラーを見つけやすくなります。例については、KerrekSBの回答を参照してください。

于 2013-01-30T12:38:39.307 に答える
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";
于 2013-01-30T12:43:19.883 に答える