C++ few beginner errors - c++

Not very good at debugging yet but I'm getting a few errors. A few expected '(' ')' and ';'
Also 'else' without a previous 'if', no match for 'operator>>' in cout
I know this is easy, but still trying to get my foot in the door. Thanks :)
#include <iostream>
#include <cstdlib>
using namespace std;
int main() // guess number game
{
int x;
cout >> "Please enter a number\n";
getline(cin x);
int y = rand();
while x != y
{
if x < y;
cout >> "Go higher";
else;
cout >> "Go lower";
}
}

cout >> "Please enter a number\n";
This is wrong, std::ostreams only provide the operator<< to insert formatted data. Use cout << "Please enter a number\n"; instead.
getline(cin x);
First, you're missing a ,, since getline needs two or three arguments. But since x is an integer and not a std::string it is still wrong. Think about it - can you store a text line inside of an integer? Use cin >> x instead.
int y = rand();
While this doesn't seem wrong there's a logical error. rand() is a pseudo random number generator. It uses a seed as start value and some kind of algorithm (a*m + b). Thus you have to specify a start value, also called seed. You can specify this by using srand(). The same seed will result in the same order of numbers, so use something like srand(time(0)).
while x != y
if x < y;
Use parenthesis. And drop the additional ;. A stray semicolon ; in your program resembles the empty expression.
EDIT: Working code:
#include <iostream>
#include <cstdlib>
#include <ctime>
int main(){
int x;
int y;
srand(time(0));
y = rand();
std::cout << "Please enter a number: ";
do{
if(std::cin >> x){
if(x < y)
std::cout << "Go higher: ";
if(x > y)
std::cout << "Go lower: ";
}
else{
// If the extraction fails, `std::cin` will evaluate to false
std::cout << "That wasn't a number, try again: ";
std::cin.clear(); // Clear the fail bits
}
}while(x != y);
std::cout << "Congratulations, you guessed my number :)";
return 0;
}

Try this:
void main()
{
int x;
cout << "Please enter a number\n";
getline(cin, x);
int y = rand();
while(x != y)
{
if(x < y)
cout << "Go higher";
else
cout << "Go lower";
}
}

Not overly familiar with C++ but i'm pretty sure the while/if should look something like this
while (x != y)
{
if (x < y)
cout << "Go higher";
else
cout << "Go lower";
}
the conditions of both if and while loops should be nested with parenthesis.

everything you listed above are syntax errors. This can be easily fixed by reading up on the syntax of c++
http://www.cs.duke.edu/csed/tapestry/howtoa.pdf
it should look more like this:
while (x != y)
{
if (x < y)
cout >> "Go higher";
else
cout >> "Go lower";
}

Let's look at all the errors:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() // guess number game
{
int x;
cout >> "Please enter a number\n"; // should be `cout <<` cin uses >>
getline(cin x); // incorrect number of arguments should be 2 or 3 plus x is an int not string could use cin instead
int y = rand();
while x != y // error condition checks should be parentheses like (x != y)
{
if x < y; // error condition should be parentheses also by adding a semicolon here you terminate the statement
cout >> "Go higher";
else; // technically not an error but unintended code is executed cout >> "Go higher" is always executed because of the semi colon ;
cout >> "Go lower";
}
// no return of value, you declared main to return an int so you should
}
Try this:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() // guess number game
{
int x;
cout << "Please enter a number\n";
cin >> x;
int y = rand();
while (x != y)
{
if (x < y)
cout >> "Go higher";
else
cout >> "Go lower";
}
return 0;
}

Related

How can I save a string input with blank space in c++ (I am using if else statement)

So I am trying to make a text multiplier , here is the code
#include <iostream>
using namespace std;
int main()
{
bool m, n;
string x;
int y;
cout << "enter how many times you want to multiply the text : ";
cin >> y;
isdigit(y);
if (y)
{
cout << "enter the text you want to multiply : ";
cin >> x;
for (int a = 1; a <= y; ++a)
cout << x << endl;
}
else
{
cout << "you did not entered a number , try again";
}
return 0;
}
Everything was fine until I came to know that it was not saving the text input with a blank space
I searched how to store string input with blank space and then changed the code but it didn't work.
The changed code was
#include <iostream>
using namespace std;
int main()
{
bool m, n;
char x[100];
int y;
cout << "enter how many times you want to multiply the text : ";
cin >> y;
isdigit(y);
if (y)
{
cout << "enter the text you want to multiply : ";
cin.getline(x, 100);
for (int a = 1; a <= y; ++a)
cout << x << endl;
}
else
{
cout << "you did not entered a number , try again";
}
return 0;
}
Please help
List item
If I understand what you want to do, you need to read the integer value, clear the remaining '\n' that is left in stdin by operator>>, and then use getline() to read the text you want to multiply, e.g.
#include <iostream>
#include <limits>
using namespace std;
int main()
{
string x;
int y;
cout << "enter how many times you want to multiply the text : ";
if (!(cin >> y)) { /* validate stream-state after EVERY input */
std::cerr << "error: invalid integer input.\n";
return 1;
}
/* clear remaining '\n' from stdin (and any other characters) */
std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
cout << "enter the text you want to multiply : ";
if (!getline (cin, x)) { /* validate stream state */
std::cout << "user canceled input.\n";
return 0;
}
for (int a = 1; a <= y; ++a)
cout << x << endl;
return 0;
}
Note: the use of isdigit(y) is superfluous. If you validate the input correctly, you determine whether a valid integer was entered at the time of the read simply by checking the stream-state after the read. If failbit is set, the user did not enter a valid integer.
While fine for test code, you will want to look at Why is “using namespace std;” considered bad practice?
Example Use/Output
$ ./bin/multiplytext
enter how many times you want to multiply the text : 3
enter the text you want to multiply : my dog has fleas
my dog has fleas
my dog has fleas
my dog has fleas
If I misinterpreted your goal, let me know and I'm happy to help further.
As seen from this answer, you are mixing the >> operator and getline() which causes syncing issues as getline is not waiting for the input to flush.
You can call either
cin.ignore();
or
cin.clear();
cin.sync();
just before getline().
Patched code:
#include <iostream>
using namespace std;
int main()
{
bool m, n;
char x[100];
int y;
cout << "enter how many times you want to multiply the text : ";
cin >> y;
isdigit(y);
if (y)
{
cout << "enter the text you want to multiply : ";
cin.ignore();
cin.getline(x, 100);
for (int a = 1; a <= y; ++a)
cout << x << endl;
}
else
{
cout << "you did not entered a number , try again";
}
return 0;
}

How can i check a variable type in a conditional statement in c++?

I am pretty new to c++ and im having an issue trying to get my program out of a loop when a string is entered for the variables cont, and answer. In python it is pretty easy to do simple checks but I am not sure what I should be doing in cpp. I tried doing a check using if(typeid(answer)) == typeid(string)) but this doesnt work. I havent tried putting a check for
'y'||'Y'||'n'||'N' for cont but im assuming it would be something like that? just check for those 4 characters?
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
int main() {
unsigned seed;
char cont = 'y';
int answer = 0;
seed = time(nullptr);
srand(seed);
rand() % 100 + 1;
cout << "Lets play a math game!\n";
while(cont == 'y')
{
int num1 = rand() % 100 + 1;
int num2 = rand() % 100 + 1;
cout << "What is the result of this addition? \n " << num1 << '\n' << "+" << num2 << endl;
cin >> answer;
if (typeid(answer)==typeid(string))
{
while(typeid(answer) == typeid(string))
{
cout << "Please enter an integer!" << endl;
cin >> answer;
}
}
else if (typeid(answer) == typeid(int)) {
if (answer == (num1 + num2)) {
cout << "You are correct, would you like to play again?" << endl;
cin >> cont;
} else {
cout << "You were incorrect, would you like to try again? enter y/n" << endl;
cin >> cont;
}
} else {
answer = 0;
cout << "You did not enter an integer!\n" << endl;
cout << "Would you like to try again?" << endl;
}
}
return 0;
}
How can i check a variable type in a conditional statement in c++?
You do that already, though I'd do this instead:
#include <type_traits>
#include <iostream>
int main() {
int answer =0;
if constexpr(std::is_same_v<int,decltype(answer)>) {
std::cout << "answer is indeed an int";
}
}
However, this will always print the expected answer is indeed an int, because answer is an int not something else. If the user enters invalid input the variable answer declared as int will not turn into a std::string.
would something like if(inRange(0,200,answer)) work?
No it would not. std::cin >> answer; either succeds to read a number, or it fails and then 0 is assigned to answer. You cannot decide if valid input was entered by looking at answer only.
To check if the user entered valid input you can check the state of the stream:
#include <iostream>
#include <limits>
int main() {
int answer =0;
while(!(std::cin >> answer)){
std::cout << "please enter a number\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cout << answer;
}
Note that this accepts for example 42asdf as valid input, because std::cin >> answer does read 42 before it encounters something that is not a number. For something more sophisticated you can read a std::string and parse that.

How do you code, if x is not equal to a number, program will then exit

I am confused about this. For example
#include <iostream>
int main(){
using namespace std;
int x, y;
cout << "enter a number: \n";
cin >> x
if (x != ){ // If user inputs anything besides a number, Program will then exit
cout << "invalid";
}
return 0;
}
what code could i use so that if the user decided to input a letter instead of a number, the program will then output invalid and the program will then exit
The operator >> used in combination with cin returns a reference that can be checked to see if the task of assigning the entry to the integer x was successful. If the operation has failed, meaning that the entry was not an integer, it returns a null pointer. In that case !(cin >> x) evaluates to true.
#include <iostream>
#include <cstdlib> // for exit()
using namespace std;
int main(){
int x;
cout << "enter a number: \n";
if (!(cin >> x) ){// If user inputs anything besides a number, Program will then exit
cout << "invalid entry.\n";
exit(0);
}
cout << "you entered number: " << x << endl;
return 0;
}
See also, e.g., the answers to this question for more information.
Edit:
As an equivalent alternative one can also use cin.fail(). This results in a code that is more easily readable:
cout << "enter a number: \n";
cin >> x ;
if (cin.fail()){
...
}

Returning value from function into a value being tested by a while loop. C++

I am creating a basic calculator program using constructors by making classes in other ".cpp" files and calling them in header files. The program worked perfectly fine the way I wrote it. I decided to then add a question at the end asking if the user would want to continue by pressing "c" or "C". I created a function to test for this. I am able to return two different values based on if c was pressed or if it was not. How do I assign that value to "x" which is being tested in the while loop? I want this to either end the program or continue it.
I did not include the header files or ".cpp" files necessary for the constructors, but I don't think they are necessary to find how to set x to the returned value of the function.
#include <iostream>
#include "Add.h"
#include "Sub.h"
#include "Mult.h"
#include "Div.h"
using namespace std;
int cont(char input);
int main()
{
char operatr;
int x = -2;
char y;
while (x = 1) {
cout << "Enter operator (+, -, *, or /): ";
cin >> operatr;
if(operatr =='+'){
Add ob;
cout << "Would you like to continue? (Press \"c\" to continue and any key to escape.)";
cin >> y;
cout << (cont(y));
x = (cont(y));
}
if(operatr== '-'){
Sub ob;
cout << "Would you like to continue? (Press \"c\" to continue and any key to escape.)";
cin >> y;
cout << (cont(y));
x = (cont(y));
}
if(operatr=='*'){
Mult ob;
cout << "Would you like to continue? (Press \"c\" to continue and any key to escape.)";
cin >> y;
cout << (cont(y));
x = (cont(y));
}
if(operatr=='/'){
Div ob;
cout << "Would you like to continue? (Press \"c\" to continue and any key to escape.)";
cin >> y;
cout << (cont(y));
x = (cont(y));
}
}
return (0);
}
int cont(char input) {
int a;
switch(input) {
case 'c':
a = -2;
break;
case 'C':
a = -2;
break;
default:
a = 0;
break;
}
return(a);
}
Couple of issues:
You're testing x being equal 1 in the loop but using -2 in your conf(int) method.
Your while loop is actually not testing x bit "assigning" 1 to x.
You meant to do:
while (x == -2)
You could also.just save on method calls to #cont with:
x = cont(y);
cout << x;

C++ can't populate data

I am trying to populate my vectors with x and y values. but it doesn't seems to add on but just override the
first.
main.cpp
#include <iostream>
#include "Point.h"
using namespace std;
int x,y;
Point point;
string options;
void someMethods();
int main()
{
cout << "Please Enter x-Cordinate"<< endl;
cin >> x;
cout << "Please Enter y-Cordinate" << endl;
cin >> y;
cout << "Enter cords again? yes/no"<< endl;
cin >> options;
while (options == "yes") {
cout << "Please Enter x-Cordinate"<< endl;
cin >> x;
cout << "Please Enter y-Cordinate" << endl;
cin >> y;
cout << "Enter cords again? yes/no"<< endl;
cin >> options;
}
if(options == "no") {
Point Point(x,y);
Point.someMethods();
// break;
}
}
Point.h
#ifndef Point_Point_h
#define Point_Point_h
#include <vector>
class Point {
private:
int x,y;
public :
Point() {
x = 0;
y = 0;
} //default consrructor
Point(int x,int y);
int getX();
int getY();
void setX(int x);
void setY(int y);
std::vector<Point> storeData;
void someMethods();
};
#endif
Point.cpp
#include <iostream>
#include "Point.h"
using namespace std;
Point::Point(int x,int y) {
setX(x);
setY(y);
}
int Point::getX() {
return x;
}
int Point::getY() {
return y;
}
void Point::setX(int x) {
this->x = x;
}
void Point::setY(int y) {
this->y = y;
}
void Point::someMethods() {
x = getX();
y = getY();
Point Point(x,y);
storeData.push_back(Point);
for (int i=0; i<storeData.size(); i++) {
cout << "X "<< storeData[i].getX() <<"Y " << storeData[i].getY() << endl;
}
// do some methods here after getting the x and y cords;
}
how can I make it such that e.g(I enter x and y 3 times let's say 1,1 2,2 3,3 )
then it will output
X: 1,Y: 1
X: 2,Y: 2
X: 3,Y: 3
int main()
{
// don't need global variables, just define local ones here
int x,y;
Point point;
string options;
// You shouldn't store the vector of Points in the Point class itself.
// It doesn't have anything to do with a Point. classes should generally
// only contain relevant information (ex. Point contains only x and y coords).
vector<Point> pointsVector;
// do-while will do the contents of the loop at least once
// it will stop when the while condition is no longer met
do
{
cout << "Please Enter x-Cordinate"<< endl;
cin >> x;
cout << "Please Enter y-Cordinate" << endl;
cin >> y;
pointsVector.push_back(Point(x, y));
cout << "Enter cords again? yes/no"<< endl;
cin >> options;
} while (options == "yes")
// don't really need to check if options is "no"
// if you have exited the do/while loop above, the assumption is that you don't
// want to enter more coordinates.
doSomethingWithTheVectorOfPoints(pointsVector);
return 0;
}
In the function doSomethingWithTheVectorOfPoints, you can place the code for outputting the X and Y coordinates. (You can also just loop through the vector in the main function directly instead.)
Also, you could add a member function to your Point class called ToString or Print to do the work for you.
Edit: I didn't actually compile this, it's just to give you an idea of how you could rewrite your code.
You should have:
No global variables
A point class supporting stream input (output)
The stored data out of the point class (why should a poor point manage that?)
Stream input with validation.
Example:
#include <iostream>
#include <stdexcept>
#include <sstream>
#include <vector>
struct Point {
int x;
int y;
};
std::istream& operator >> (std::istream& in, Point& point) {
return in >> point.x >> point.y;
}
typedef std::vector<Point> PointStorage;
int main()
{
PointStorage point_storage;
Point point;
while(true) {
std::cout << "Please enter X and Y xordinates or 'no' to stop input" << std::endl;
std::string line;
if( ! std::getline(std::cin, line))
throw std::invalid_argument(line);
else {
std::istringstream point_input(line);
// Skip leading white spaces, read a point, skip trailing white apace
// and ensure no additional character is left.
if(point_input >> point >> std::ws && point_input.eof()) {
point_storage.push_back(point);
}
else {
std::string no;
std::istringstream no_input(line);
// Skip leading white spaces, read "no", skip trailing white apace
// and ensure no additional character is left.
if(no_input >> no >> std::ws && no_input.eof() && no == "no") {
break;
}
throw std::invalid_argument(line);
}
}
}
for(PointStorage::const_iterator pos = point_storage.begin();
pos != point_storage.end();
++pos)
{
std::cout << pos->x << ", " << pos->y << '\n';
}
return 0;
}
Note: Throwing exceptions is likely a bad decision, but it simplifies the example.
You re-create your Point object with the final coords every time you enter "no". This is why you only keep the last pair.
On an unrelated note, you should probably simplify the code significantly. There is no reason for Point object to keep a vector of Point objects in the first place. You probably want to keep a history/sequence of raw coordinates there and have something like:
Point mypt;
while (options == "yes") {
mypt.AddCoords(x, y);
// read more coords/options
}
// do stuff on filled mypt object