Hi,

I just like to know, can an input data from user (keyed in) be compared with data contained in a files (.txt). Because, I need to compare one data (string) to so many strings or a group of data (about 100+). Therefore, I like to avoid from using so many "OR" in the code.

If not, is there any suggestion on how to simplify this.

TQ

//Example:

#include<iostream>
#include<string>
using namespace std;

int main()
{

string userdata;

cout << "Please enter the data: ";
cin >> userdata;

if ((userdata=="abc111") || (userdata=="abc112") || (userdata=="abc113") || (userdata=="abc114") || (userdata=="abc115") || (userdata=="abc116"))

cout << "The data is correct";

else cout << "The data is incorrect";

return 0;
}

One way would be to make an array of valid strings then loop through that array

string valid[] = {"abc111","abc112","abc1113", ... };
bool ok = false;
for(int i = 0; i < sizeof(valid)/sizeof(valid[0]); i++)
{
   if( userdata == valid[i])
   {
      ok = true;
      break;
   }
}

if( ok == true)
{
   // blabla
}

Just another way, use stl::map;

#include <iostream>
#include <map>
#include <string>
#include <vector>

using namespace std;


int main(){
	std::map<string,int> dict;
	std::vector< pair<string,int> > vec;
	vec.push_back( make_pair("basketball",0));
	vec.push_back( make_pair("soccer",0));
	vec.push_back( make_pair("tennis",0));
	vec.push_back( make_pair("football",0));
	vec.push_back( make_pair("swimming",0));

	dict.insert(vec.begin(),vec.end());

	string input;	
	cout << "Enter a sport and see if I have it\n<input>";
	while(cin >> input){
		if(dict.find( input ) != dict.end() ){
			cout << "I have it in my dictionary\n";
		}
		else cout << "sorry, I don't have it\n";
		cout << endl << "<input>";
	}

}

I would recommend it using this way, if you list of words are very large or even
mildly big.

This article has been dead for over six months. Start a new discussion instead.