
Originally Posted by
JunkZ
Super c++ noob here, how do I make it so if the user types "end" the program will close and if they type something else it will: cout << "a";
This is everything ive found on the internet.
cout << "Type end to close" <<endl;
string type;
if(type == "end")
{
return (0);
}
else
cout << "a";
}
This would be the correct code (mpgh didn't let me tab...):
Code:
#include <stdio.h>
#include <stdlib.h>
#include <iostream.h>
#include <string>
using namespace std; //you won't have to std:: everytime.
int main()
{
string type; //inizialize type
cout<<"Type end to close"<<endl; //ask to cin
cin>>type; //cin
if(type=="end")
{
//do the stuff
}
else
{
//do other stuff
}
system("pause"); ( or getchar(); )
return 0;
}
a few general rules:
1) Inizialize everything at the beginning,not in the middle of your program.
2) The program must start at the beginning and finish at the end,if you make something like:
Code:
cin>>a;
if(a>0)
return 0;
else
cout<<"funneh";
return 0;
Then you gotta not use such thing.
While a computer will never say it's not fine,it creates alot of confusion and is globally avoided as much as possible.
A trick to fix this is to use a bool variable and setting it to true to any possible correct value,then the program will continue only if that variable is true,example:
Code:
//Program outputs "hello" only if a>5 and b<3
int a,b;
bool valuesarevalid=false;
cin>>a>>b;
if(a>5 && b<3)
valuesarevalid=true;
if(valuesarevalid==true)
cout<<"hello"<<endl;
system("pause");
return 0;