2

I have a .txt file which contains a continuous sequence of characters (without spaces). I wanted to search for a sequence of characters in the .txt file and am having trouble doing that.

ifstream fin;
    fin.open("sample.txt");
    while (!fin.eof())
    {
        ch = getchar();
        if (ch == 'p' && ch + 1 == 'o' && ch + 2 == 'w')
            std::cout << "Sequence found" << "\n";
    }
    fin.close();
Raisa A
  • 437
  • 7
  • 21
  • Consider the following program: `int main() { char c = 'p'; std::cout << c << c + 1 << c + 2; }`. Will it print `pow`? – molbdnilo Feb 22 '19 at 07:38
  • Unrelated, but still a major problem with your code: [Why is `iostream::eof` inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – molbdnilo Feb 22 '19 at 07:39
  • You need to create a byte buffer (for instance an byte array) and then invoke the `.read(buffer, bufferSize)` function on the `fin` to read from the file to the buffer. Check the example here: http://www.cplusplus.com/reference/istream/istream/read/ – Chris623 Feb 22 '19 at 07:40

1 Answers1

2

That won't work, ch is the character you read in, but ch + 1 isn't the next character (that you haven't read in yet). It's just ch increased by 1, so that's the next letter in the alphabet, the digit one bigger, etc. depending on what ch is anyway.

If you just want to see whether a sequence is in a file, then I would read in the file into an std::string like this answer says:

std::string slurp(std::ifstream& in) {
    std::stringstream sstr;
    sstr << in.rdbuf();
    return sstr.str();
}

So you pass that function your fin and you get a string containing your file's content. Then you try to find your sequence like this answer explains:

if (myString.find("pow") != std::string::npos) {
    std::cout << "found!" << '\n';
}
Blaze
  • 16,736
  • 2
  • 25
  • 44