Problems with using if, then statement - c++

This is what I have so far. I have been testing it on c++ shell and it gives me error.
#include <iostream>
#include <string>
int main() {
cout << "Enter a number between 3 and 12: ";
int n;
cin >> n;
if(n>=3 && n<=12)
cout<<"Good number."endl;
else
cout<<"Bad number"endl;
return 0; //indicates success
}//end of main

cout,cinand endl are part of the standard library so you need to use std::cout, std::cin and std::endl. You can use using namespace std; on the beginning as well (after the includes, but it is considered as bad programming style).
Change your output to:
std::cout << "Good number." << std::endl;
Here is a working example:
int main() {
std::cout << "Enter a number between 3 and 12: ";
int n;
std::cin >> n;
if(n>=3 && n<=12)
std::cout<<"Good number."<<std::endl;
else
std::cout<<"Bad number"<<std::endl;
return 0; //indicates success
}

Related

"noskipws" works but doesn't stop in c++

I am trying to write a program that checks if a phrase is a palindrome or not, and in case nothing is entered or just whitespace, it should print out "empty".
At first, the user should type in the number of phrases that they are going to enter (e.g. 3), and then the phrases that are to be checked.
It works just fine, but when my first input is empty, it prints out "empty" again and again without asking for another phrase.
#include <iostream>
#include <string>
#include <iomanip>
#include <math.h>
using namespace std;
int main() {
int N;
int isPalindromeCounter=0;
int counter = 0;
string inputString;
cin >> N;
cout << "\n";
while (counter<N){
counter++;
cin.ignore(100, '\n');
cin >> noskipws >> inputString;
if (inputString.length()==0){
cout <<"empty\n";
continue;
}
int left = 0;
int right = inputString.length()-1;
if (inputString.length()>20){
cout <<"error\n";
continue;
}
bool isPalindrome = true;
while (left<right){
if (inputString[left] != inputString[right]){
isPalindrome = false;
cout << "no\n";
break;
}
left++;
right--;
}
if (isPalindrome){
cout << "yes\n";
isPalindromeCounter++;
}
}
double percentage = double(isPalindromeCounter)/double(counter)*100;
if (trunc(percentage) != percentage){
cout << setprecision(5) << percentage;
}
else {cout << percentage << ".000" ;}
return 0;
}
What am I doing wrong ?
I expected that it should print "empty" once, and then ask for another input, but it prints "empty" for all the inputs.

C++ Exception handling Inside loop not working [duplicate]

I am just trying to write a simple program that reads from cin, then validates that the input is an integer. If it does, I will break out of my while loop. If not, I will ask the user for input again.
My program compiles and runs just fine, which is great. But it doesn't prompt for new input if I enter a non numeric value. What gives?
#include <iostream>
using namespace std;
int main() {
bool flag = true;
int input;
while(flag){
try{
cout << "Please enter an integral value \n";
cin >> input;
if (!( input % 1 ) || input == 0){ break; }
}
catch (exception& e)
{ cout << "Please enter an integral value";
flag = true;}
}
cout << input;
return 0;
}
C++ iostreams don't use exceptions unless you tell them to, with cin.exceptions( /* conditions for exception */ ).
But your code flow is more natural without the exception. Just do if (!(cin >> input)), etc.
Also remember to clear the failure bit before trying again.
The whole thing can be:
int main()
{
int input;
do {
cout << "Please enter an integral value \n";
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
} while(!(cin >> input));
cout << input;
return 0;
}
Don't use using namespace std; Instead import what you need.
It's better to do input a line at a time. This makes behavior much more intuitive if you have multiple words on one line, or if you press enter before typing anything.
#include <iostream>
#include <sstream>
#include <string>
using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::flush;
using std::getline;
using std::istringstream;
using std::string;
int main() {
int input;
while (true)
{
cout << "Please enter an integral value: " << flush;
string line;
if (!getline(cin, line)) {
cerr << "input failed" << endl;
return 1;
}
istringstream line_stream(line);
char extra;
if (line_stream >> input && !(line_stream >> extra))
break;
}
cout << input << endl;
return 0;
}

Cannot get my getchar() function to work how I want it to work, output is10 not 2 c++

I cannot figure out why my getchar() function is not working the way I want it to work. I am getting 10 not 2. Please take a look.
Main():
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int var, newvar;
cout << "enter a number:" << endl;
cin >> var;
newvar = getchar();
cout << newvar;
return 0;
}
Here is my output:
enter a number:
220
10
Ultimately though I need to be able to distinguish between a '+' '-' or letter or number.
This is maybe not the cleanest way to do it but you can get every char one by one :
#include <iostream>
using namespace std;
int main()
{
int var;
cout << "enter a number:" << endl;
cin >> var;
std::string str = to_string(var);
for(int i=0; i < str.length();++i)
cout << str.c_str()[i] << endl;
return 0;
}
If you enter for example: "250e5" it will get only 250 and skip the last 5.
Edit:
This is just a simple parser and does not do any logic.
If you want to make a calculator I would recommend you to look at what Stroustrup did in his book the c++ programming language.
int main()
{
string str;
cout << "enter a number:" << endl;
cin >> str;
for(int i=0; i < str.length();++i) {
char c = str.c_str()[i];
if(c >= '0' && c <= '9') {
int number = c - '0';
cout << number << endl;
}
else if(c == '+') {
// do what you want with +
cout << "got a +" << endl;
} else if(c == '-')
{
// do what you want with -
cout << "got a -" << endl;
}
}
return 0;
}

char uninitialized, isnumber method unidentified,

I'm having errors in my code below,
This is my code:
#include "stdafx.h"
#include <vector>
#include <iostream>
using namespace std;
int main(){
vector<int> numbers(0);
cout << "please enter you numbers :::\n''entering any characters but numbers is the end of entry''";
char ch;
int i = 0;
while (Isnumber(ch)){ //here is the error
do{
ch = getchar();
int newnumber = 0;
cout << "element(" << i << ") = ";
cin >> newnumber;
numbers.push_back(newnumber);
} while (ch>0 || ch < 9);
}
getchar();
}
two errors,
it says that identifier is unknown,
and
it says variable char is uninitialazed local variable,
change this while (Isnumber(ch)){ into do-while loop.
do{
.....
}while (Isnumber(ch))
The error is because ch is declared and it is used before initialized.
Also include #include <stdio.h>; for getchar();
Better do it in one loop:
do {
ch = getchar();
int newnumber = 0;
cout << "element(" << i << ") = ";
cin >> newnumber;
numbers.push_back(newnumber);
} while (Isnumber(ch)); // should probably be isdigit(ch)
And before asking similar questions read this first (or buy a book).
Well I solved it using cin functions as below,
#include "stdafx.h"
#include <vector>
#include <iostream>
using namespace std;
int main(){
vector<int> numbers(0);
cout << "please enter you numbers :::\n''entering any characters but numbers is the end of entry''\n";
//char ch;
int counter = 0;
do{
int newnumber = 0;
cout << "element(" << counter << ") = ";
counter++;
cin >> newnumber;
numbers.push_back(newnumber);
if (cin.fail()){
cout << "entered numbers are:\n";
for (vector<int>::iterator i = numbers.begin(); i != numbers.end(); i++)
{
cout << *i;
if (i != numbers.end()-1)cout << " - ";
}
}
} while (cin.good());
getchar();
}
I removed one while loop.
and used cin.fail and cin.good to avoid using IsNumber. And it worked.

std::cin doesn't throw an exception on bad input

I am just trying to write a simple program that reads from cin, then validates that the input is an integer. If it does, I will break out of my while loop. If not, I will ask the user for input again.
My program compiles and runs just fine, which is great. But it doesn't prompt for new input if I enter a non numeric value. What gives?
#include <iostream>
using namespace std;
int main() {
bool flag = true;
int input;
while(flag){
try{
cout << "Please enter an integral value \n";
cin >> input;
if (!( input % 1 ) || input == 0){ break; }
}
catch (exception& e)
{ cout << "Please enter an integral value";
flag = true;}
}
cout << input;
return 0;
}
C++ iostreams don't use exceptions unless you tell them to, with cin.exceptions( /* conditions for exception */ ).
But your code flow is more natural without the exception. Just do if (!(cin >> input)), etc.
Also remember to clear the failure bit before trying again.
The whole thing can be:
int main()
{
int input;
do {
cout << "Please enter an integral value \n";
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
} while(!(cin >> input));
cout << input;
return 0;
}
Don't use using namespace std; Instead import what you need.
It's better to do input a line at a time. This makes behavior much more intuitive if you have multiple words on one line, or if you press enter before typing anything.
#include <iostream>
#include <sstream>
#include <string>
using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::flush;
using std::getline;
using std::istringstream;
using std::string;
int main() {
int input;
while (true)
{
cout << "Please enter an integral value: " << flush;
string line;
if (!getline(cin, line)) {
cerr << "input failed" << endl;
return 1;
}
istringstream line_stream(line);
char extra;
if (line_stream >> input && !(line_stream >> extra))
break;
}
cout << input << endl;
return 0;
}