#include <iostream>
#include<string>
using namespace std;
int main()
{
int i;
cin>>i;
string s1;
if(i==1)
{
string s1 = "Hello";
}
else if (i==2)
{
string s1 = "byebye";
}
cout<<s1; //the output does not come out
#include <iostream>
#include<string>
usingnamespace std;
int main()
{
int i;
cin>>i;
string s1{"default"}; //initial values on all variables is a good practice.
//strings and most objects do this for you and are created "empty string (or empty object)"
//but integers and doubles and other basic types have random initial values if not set
if(i==1)
{
s1 = "Hello\n"; // \n adds an end of line.
}
elseif (i==2)
{
s1 = "byebye\n";
}
cout<<s1; //the output does not come out
}
Hint: You can edit your post, highlight your code and press the <> formatting button. This will not automatically indent your code. That part is up to you.
You can use the preview button at the bottom to see how it looks.
#include <iostream>
#include <string>
usingnamespace std; // <--- Best not to use.
int main()
{
int i{}; // <--- ALWAYS initialize all your variables.
// <--- The "cin" ALWAYS needs a prompt.
cin >> i;
string s1; // <--- Only needs defined once.
if (i == 1)
{
string s1 = "Hello";
}
elseif (i == 2)
{
string s1 = "byebye";
}
cout << s1; //the output does not come out
return 0; // <--- Not required, but makes a good break point for testing.
}
A few blank lines and proper indenting make a big difference.
Lines 16 and 18 create a block for the if statement. Defining a variable inside the block makes it local to the block and when line 18 is reached that variable is destroyed because the scope is no longer in the block for the if statement. The same is true for the else statement.
Since lines 17 and 21 are destroyed at the closing } of the block only the "s1" at line 13 is available for the "cout" at line 24.
When you reach line 11 you may know what to enter, but anyone else running the program does not. You need a prompt at line 10 to tell the user what to enter.
Always is a strong word :)
I have a number of programs that expect their input to come from a file redirected into them for automation, and prompting serves no purpose. Here, yes, it needs one.
Hmm. If the program is designed to be used interactively, then probably yes, a prompt should be first displayed.
However, if file redirection is used, then cin would be referring to a file - and not to the keyboard - and in this case a prompt may not be needed - as it would show unnecessarily.