+ 2

C++ problems with cin, cout and the if statement.

Hey guys, I am pretty new to this but thought this would be the best place to start. I am trying to make a piece of code that when the letter a is input, it will display "4x". Likewise when the letter b is input it will display "6x^2". It works perfectly when I input 'a' but for some reason whenever I input 'b' it displays "No Output". All help would be greatly appreciated! I've tried doing it 2 ways, but neither work. #include <iostream> #include <cctype> #include <cmath> using namespace std; int main() { char a; char b; cin >> a; cin >> b; if (a == 'a'|| a == 'A') cout << "4x"; else if (b == 'b'|| b == 'B') cout << "6x^2"; } Method 2 : #include <iostream> #include <cctype> #include <cmath> using namespace std; int main() { char a; cin >> a; if (a == 'a'|| a == 'A') cout << "4x"; char b; cin >> b; if (b == 'b'|| b == 'B') cout << "6x^2"; }

29th Mar 2018, 2:28 PM
TGFoxy
TGFoxy - avatar
6 Respuestas
+ 8
You only need one variable to achieve what you are doing. char a; cin >> a; if (a == 'a' || a == 'A') cout << "4x"; else if (a == 'b' || a == 'B') cout << "6x^2"; The reason why your examples are not working for b is because your program expects the user to input to both variable a and b, but only received one input.
29th Mar 2018, 2:34 PM
Hatsy Rei
Hatsy Rei - avatar
+ 2
Your code works, but not as you expect. You need to input 2 chars, because you have 2 cin for 2 variables. And if the first is true then the 2nd will be ignored. I guess you want something like char input; cin >> input; if (input == 'a' || input == 'A') cout << "4x"; else if (input == 'b' || input == 'B') cout << "6x^2";
29th Mar 2018, 2:36 PM
Alex
Alex - avatar
+ 2
Thank you so much Hatsy! Was banging my head off the wall trying to figure that one out! Thank you also Alex! Very helpful both of you.
29th Mar 2018, 2:36 PM
TGFoxy
TGFoxy - avatar
+ 1
you have typed std::<<
2nd Apr 2018, 6:42 PM
Karthik Mamillapalli
Karthik Mamillapalli - avatar
0
Hello everybody. I have some problems with my code. Compilator shows me that string statement cannot be used here: # include <iostream> using namespace std; int main() { string name; cout<<"введите имя математического действия"; cin>>name; if (name=='сложение') { float a,b,c; cout<<"1 число="; cin>>a; cout<<"2 число="; cin>>b; c=a+b; std::<<cout"a+b="<<c<<std::endl; } if (name=='вычитание') { float a,b,c; cout<<"1 число="; cin>>a; cout<<"2 число="; cin>>b; c=a-b; std::cout<<"a-b="<<c<<std::endl; } if (name=='умножение') { float a,b,c; cout<<"1 число="; cin>>a; cout<<"2 число="; cin>>b; c=a*b; std::cout<<"a*b="<<c<<std::endl; } }
1st Apr 2018, 1:25 PM
Иван Поддубный
Иван Поддубный - avatar
0
Yeah, cout is used as "std::cout << 'text'". Also, not sure, but usually when working with string types, #include <string>
12th Apr 2018, 12:34 AM
Daniel Garner
Daniel Garner - avatar