Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
82 views
in Technique[技术] by (71.8m points)

c++ - Switch case is printing only default value

#include<iostream>
#include<algorithm>
using namespace std;
int main(){
int n;
//only printing the default value
cout<<"Press 1 for Hindi, Press 2 for English, Press 3 for Punjabi,   ess 4 for Japanese."<<endl;
cin>>n;
switch (n)
{ 
case '1':
cout<<"Namaste";
    break;
case '2':
cout<<"Hello";
break;
case '3':
cout<<"Sat Shri Akal";
case '4':
cout<<"Ohaio gosaimas";
break;
default:
cout<<"I am still learing more!!!";
}
      return 0;
}
question from:https://stackoverflow.com/questions/65840260/switch-case-is-printing-only-default-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issue is that n is an integer type but in the switch statemen, your comparing it against chars.

You can use either of these two options to fix it,

  1. Change n to be a char type.
  2. Change the comparation to be an integer type.

For option 1, its a simple change.

char n;

For option two, change the '1', '2', '3', ... to 1, 2, 3, ...

switch (n) {
case 1:
    ...
    break;
case 2: 
    ...
    break;
...
}

Make sure you don't mix up integers and characters specially when comparing!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...