次のようなテストファイルがあります。
Ampersand Gregorina 5465874526370945
Anderson Bob 4235838387422002
Anderson Petunia 4235473838457294
Aphid Bumbellina 8392489357392473
Armstrong-Jones Mike 8238742438632892
コードは次のようになります。
#include <iostream>
#include <string>
#include <fstream>
class CardSearch
{
protected:
std::ifstream cardNumbers;
public:
CardSearch(std::string fileName)
{
cardNumbers.open(fileName, std::ios::in);
if (!cardNumbers.is_open())
{
std::cout << "Unable to open: " << fileName;
}
return;
}
std::string Find(std::string lastName, std::string firstName)
{
// Creating string variables to hold first and last name
// as well as card number. Also creating bools to decide whether
// or not the person has been found or if the last name is the only
// identifier for a found person
std::string lN;
std::string fN;
std::string creditNumber;
bool foundPerson = false;
// By using the seekg and tellg functions, we can find our place
// in the file and also calculate the amount of lines within the file
cardNumbers.seekg(0, std::ios::beg);
cardNumbers.clear();
std::streamsize first = cardNumbers.tellg();
cardNumbers.ignore(std::numeric_limits<std::streamsize>::max());
cardNumbers.clear();
std::streamsize last = cardNumbers.tellg();
cardNumbers.seekg(0, std::ios::beg);
std::streamsize lineNumbers = (last / 57);
std::streamsize middle;
while (first <= lineNumbers)
{
middle = (first + lineNumbers) / 2;
// middle * 57 takes us to the beginning of the correct line
cardNumbers.seekg(middle * 57, std::ios::beg);
cardNumbers.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cardNumbers >> lN >> fN;
if (lN < lastName)
{
first = middle + 1;
}
else if (lN > lastName)
{
lineNumbers = middle - 1;
}
else
{
if (fN < firstName)
{
first = middle + 1;
}
else if (fN > firstName)
{
lineNumbers = middle - 1;
}
else if (fN == firstName)
{
foundPerson = true;
break;
}
}
}
if (foundPerson)
{
// When a person is found, we seek to the correct line position and
// offset by another 40 characters to receive the card number
cardNumbers.seekg((middle * 57) + 40, std::ios::beg);
std::cout << lN << ", " << fN << " ";
cardNumbers >> creditNumber;
return creditNumber;
}
return "Unable to find person.\n";
}
};
int main()
{
CardSearch CS("C:/Users/Rafael/Desktop/StolenNumbers.txt");
std::string S = CS.Find("Ampersand", "Gregorina");
std::cout << S;
std::cin.ignore();
std::cin.get();
return 0;
}
リストの最初のレコードを除くすべてを取得できます。seekg は正しい位置にシークしているように見えますが、cardNumbers は正しい情報を読み取っていません。'middle' が 0 に設定されている場合、seekg は 0 行目 (middle * 57) をシークし、アンパサンド グレゴリーナを読み取り、比較を行う必要があります。代わりに、Anderson Bob を読み続けます。
なぜこれが起こっているのかについてのアイデアはありますか?
ありがとう