If statement in for loop problem

Hello. I seem to be having a bit of problem with my if statements in a for loop.

My code involves asking the user for the name of an element (chemistry), searching a text file line by line for an element that matches the input, and outputting other information regarding that element.

One line of the text file looks like this: Helium,He,2,4.00

I've tried running the code without the if loop and it outputs normally (If I ask it to output elementname[0] it will output the first element Hydrogen, which is correct.) but I am not sure what goes wrong when I add the if statement. For some reason, it always follows the "else" statement (It always outputs Invalid search even when I input the right elements).

Some help would be appreciated. Thanks! :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//MY CODE

const int ELEMENTS = 118; //number of elements
ifstream File;
string elementname[ELEMENTS], atomicsymbol[ELEMENTS], atomicnumber[ELEMENTS], atomicmass[ELEMENTS];
string elemname, atomsym, atomnum, atommass;
string search;

cout << "Enter element name: " << endl; //asks for element
cin >> search; //stores input
File.open("Elements.txt"); //opens txt file

for(int i = 0; i < ELEMENTS; i++) 
{
	getline(File, elementname[i], ',');
	getline(File, atomicsymbol[i], ',');
	getline(File, atomicnumber[i], ',');
	File >> atomicmass[i];
    if (search==elementname[i]){ 
		cout << elementname[i] << endl;
		cout << atomicsymbol[i] << endl;
		cout << atomicnumber[i] << endl;
		cout << atomicmass[i] << endl;
		break;
	}else{
		cout << "Invalid search" << endl;
		break;
	}
}
	File.close(); //closes file
	system("PAUSE");
	return 0;
The problem is with else statement.

When you enter element name it starts searching for element, compares first element (Hydrogen) with your string, sees that they aren't equal and runs else statement, where it first outputs "invalid search" and hen terminates loop.

If you delete break from else, you will see your program outputting "invalid search" n-1 times where n is the element number.

Also you should change line 18 to use getline too, or it probably will not find anything too.


If you want to incorporate this code into larger program and run search multiple times, it is better to load file into container first and then run searches on it without need to access file over and over. And instead of using several arrays you should define a structure holding element details.
Last edited on
Thank you! That solved my problem :D thank you also for your additional advice.
Topic archived. No new replies allowed.