I want to check if the chosen strings appear in the same line. Sadly I don't get the correct output. The file contains this text
/* one
two
one two
two one
two
one
something
else */
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void display(ifstream& MyFile, string a, string b)
{
string s="";
int choice;
cout << "Choose the mode you want to use " << endl;
cout << "1. Find both words" << endl;
cout << "2. Find one words" << endl;
cout << "3. Find where there is none words" << endl;
cout << "Choose the mode you want to use : ";
cin >> choice;
switch (choice) {
case 1:
while (getline(MyFile, s))
{
if (s.find_first_of(a, 0) && (s.find_first_of(b, 0)) )
{
cout << "Found both words" << endl;
}
}
break;
case 2:
while (getline(MyFile, s))
{
if ((s.find_first_of(a, 0) && !s.find_first_of(b, 0)) || (!s.find_first_of(a, 0) && s.find_first_of(b, 0) ))
{
cout << "Found one word" << endl;
}
}
break;
case 3:
while (getline(MyFile, s))
{
getline(MyFile, s);
if (!s.find_first_of(a, 0) && !s.find_first_of(b, 0))
{
cout << "No words " << endl;
}
}
break;
default:
cout << "Wrong Input" << endl;
}
}
int main()
{
ifstream Myfile("Mydata.dat");
string a = "one", b = "two",fileData;
display(Myfile, a, b);
Myfile.close();
return 0;
}
I get "Found both words" 5 times whereas it should be 2. The same thing happens with the other options. My
thoughts are that in the if
statement I compare the function s.find_firstof(str, pos)
wrongly because this function returns the index of the first instance in s
of any character in str
, starting the search at position pos
. My second thought is that I read the data of the file wrong.
Found both words
Found both words
Found both words
Found both words
Found both words