Code Not taking string

When i start the program it successfully asks for the "identifier" variable, however when it gets to the getline it just skips it and ends the program

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
33
34
  #include <iostream>
#include <string>

using namespace std;
void Hydrogen();
void Helium();
int main()
{
	string name;
	int identifier;
	cout<<"Periodic Table"<<endl;
	cout<<"Enter Name(1), Symbol(2), or atomic Number(3): "<<endl;
	cin>>identifier;

	if(identifier==1){
		cout<<"Enter Name: ";
		getline(cin, name);

		if(name == "hydrogen"){
			void Hydrogen();
		}

	}
	
system("pause");
return(0);
}
void Hydrogen()
{
	cout<<"  H"<<endl;
	cout<<"Hydrogen"<<endl;
	cout<<"   1    "<<endl;
	cout<<"1.008"<<endl;
}
@ModcaFox

Try changing
1
2
3
if(name == "hydrogen"){
		void Hydrogen();
		}


to..

1
2
3
if(name == "hydrogen"){
		Hydrogen();
		}


You do not put anything in front of the call to functions.
This should fix it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
	if(identifier==1)
	{
		cin.ignore();  // ignores previous input
		cout<< "Enter Name: ";
		std::getline(std::cin,name);

		if(name == "hydrogen")
		{
			Hydrogen(); // remove void
		}
		else
		{
		cout << "*Error*"<< name;
			
		}

	}
Last edited on
i did that and the problem persists. the program terminates just after i enter a value for the "cin>>identifier".
Since you're mixing the extraction operator>> and getline() it is possible that you are getting tripped up by the newline that the extraction operator>> leaves in the input buffer. Try modifying your getline() to : getline(cin >> ws, name); and remember C++ is case sensitive "Hydrogen" is not the same as "hydrogen".



I got it working now, thanks for the help
Mind sharing the fix?
closed account (48T7M4Gy)
getline() isn't necessary ...

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
33
34
  #include <iostream>
#include <string>

using namespace std;
void Hydrogen();
void Helium();
int main()
{
	string name;
	int identifier;
	cout<<"Periodic Table"<<endl;
	cout<<"Enter Name(1), Symbol(2), or atomic Number(3): "<<endl;
	cin>>identifier;

	if(identifier==1){
		cout<<"Enter Name: ";
		cin >> name; // <---

		if(name == "hydrogen"){
			Hydrogen(); // <---
		}

	}
	
system("pause");
return(0);
}
void Hydrogen()
{
	cout<<"  H"<<endl;
	cout<<"Hydrogen"<<endl;
	cout<<"   1    "<<endl;
	cout<<"1.008"<<endl;
}
Periodic Table
Enter Name(1), Symbol(2), or atomic Number(3): 
1
Enter Name: hydrogen
  H
Hydrogen
   1    
1.008
 
Exit code: 0 (normal program termination)


BTW Having separate functions for each element is a very cumbersome way of doing things. Arrays and vectors, classes annd structs are key considerations to improving this program.
Topic archived. No new replies allowed.