Sorry if this is REALLY trivial, I'm just sick at being stuck at step one and need to continue and I have no help anywhere else. I can not for the life of me get this function to cooperate with me. Here's the source:
#include <iostream>
using namespace std;
void ReadDials(){
};
void ToDigit(char *x){
if (*x = 'a'){*x = '54';}
else if (*x = 'A'){*x = 2;}
else if (*x = 'b'){*x = 3;}
else(*x = 4);
};
int main()
{
char one;
char two;
char three;
cin >> one;
ToDigit(&one);
cout << "one is: " << one << endl;
system("PAUSE");
}
What I've tried: alternating between the actual number 2 and the ascii pointer of 2 which I believe is '32' I've used == to try, I've done everything I can possibly think of and I know I'm over thinking it. The point is to have that function convert user input into numbers for a phone dialer.
Problems ranging from numbers not syncing with if statements, and seeing a ':D' face on the console. It's making me very annoyed.
If I need to make myself more clear, I'll be more than happy too.
Thanks in advance for any assistance.
In if (*x = 'a'), the = is an assignment. You want == for comparison. Also, '54' isn't a character value.
void ToDigit(char *x){
if (*x == 'a') { *x = '54'; } /* what is this supposed to do? */
else if (*x == 'A') {*x = 2; }
else if (*x == 'b') {*x = 3; }
else { *x = 4 };
};
It looks like you are trying to use x as an input and output. Let's step back a minute. Let's instead write a function that takes a single char and returns an integer. This would be the canonical way of taking a char and getting a number from it.
int ToDigit(char x){
if (x == 'a') { return 54; }
if (x == 'A') { return 2; }
if (x == 'b') { return 3; }
return 4 ;
};
To use this form of the function, you'd assign the return value to a variable of type int in this case.
char my_input;
int mapped_number;
std::cin >> my_input;
mapped_number = ToDigit(my_input);
std::cout << my_input << " maps to " << mapped_number << ".\n";
Related
I have used references for strings 's' and 'x' because I thought that in function call stack, each call will have its separate copy of strings 's' and 'x' and it will tax program's performance.
So does this actually helps ? ( I am not asking for an alternative solution of Palindrome checking.)
bool checkPalindrome(string &s,string &x,int indexToExtract){
if(indexToExtract < 0){
if(s == x){
return true;
}else{
return false;
}
}
x = x + s[indexToExtract];
return checkPalindrome(s,x,indexToExtract - 1);
}
int main(){
string x = "sassas";
string y = "";
cout << checkPalindrome(x,y,x.size() - 1);
}
I was trying to make a script for a math thing that a saw and I got the following error...
line 23|error: invalid initialization of non-const reference of type 'std::__cxx11::string&' {aka 'std::__cxx11::basic_string&'} from an rvalue of type 'bool'|
I am pretty new to c++ and I tried to search this problem on the internet, but nothing works. Can you please help me?? (code below btw)
#include <string>
#include <math.h>
using namespace std;
bool hasEnding (std::string &fullString, std::string &ending) {
if (fullString.length() >= ending.length()) {
return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending));
} else {
return false;
}
}
int main() {
int current_num;
bool odd;
bool even;
cout << "Type a positive number: "; // Type a number and press enter
cin >> current_num;
while (current_num >= 2) {
std::string s = std::to_string(current_num);
cout << s << endl;
odd = hasEnding (s, "1"||"3"||"5"||"7"||"9");
even = hasEnding (s, "0"||"2"||"4"||"6"||"8");
if (odd == true) {
current_num = current_num*3;
current_num = current_num+1;
}
if (even == true) {
current_num = current_num/2;
}
}
return 0;
}
Thanks to the people in the comments... I fixed it by finding a thing that checks if a number in even or odd instead of making a very inefficient script which checks the last number. The solution for it was n % 2 == 0
Hate coming back for help after getting help on the same program just a few days ago, but I am really struggling to finish this program. In short, I need to create a postfix notation calculator (RPN) with a linked list stack, that allows me to do expressions such as 5 5 5 + + (=15). I've managed to get the main calculation part down now, but I am struggling with handling two of the errors. One of which is "too many operators," and the other, "too many operands." Currently working on "too many operators" and I feel like I am close but can't quite get there.
If the user enters 5 5 + + on the first entry, it catches it and says "too many operands." However, if something is already in the stack from a previous calculation, and they then type the same expression 5 5 + +, it is not saying that the stack is empty, and is instead outputting an answer with the previous number being used. If anyone can see where I am going wrong here, and also point me in a direction for figuring out the other error "too many operators" (ex: 5 5 5 +) that'd be greatly appreciated. Thanks again in advance.
(After messing with it more, it seems the more calculations I do, the more operators actually need to be put in place to be considered empty. I'm guessing I need to popVal somewhere before each expression but not sure where to put it, as I've tried many places and it's not working)
#include<iomanip>
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
class SLLNode
{
double data;
SLLNode *top;
SLLNode *ptr;
public:
SLLNode()
{
top = NULL;
ptr = NULL;
}
bool isEmpty()
{
return top == 0;
}
void pushVal(double val)
{
SLLNode *next = new SLLNode;
next -> data = val;
next -> ptr = top;
top = next;
}
double popVal()
{
if (isEmpty())
{
cout << "Error: Too many operators" << endl;
}
else
{
SLLNode *next = top -> ptr;
double ret = top -> data;
delete top;
top = next;
return ret;
}
}
void print()
{
cout << top -> data << endl;
}
};
bool isOperator(const string& input)
{
string ops[] = {"+", "-", "*", "/"};
for(int i = 0; i < 4; i++)
{
if(input == ops[i])
{
return true;
}
}
return false;
}
void performOp(const string& input, SLLNode& stack)
{
double fVal, sVal;
int errorCheck = 0;
sVal = stack.popVal();
fVal = stack.popVal();
if(input == "+")
{
stack.pushVal(fVal + sVal);
}
else if(input == "-")
{
stack.pushVal(fVal - sVal);
}
else if(input == "*")
{
stack.pushVal(fVal * sVal);
}
else if(input == "/" && sVal != 0)
{
stack.pushVal(fVal / sVal);
}
if(input == "/" && sVal == 0)
{
cout << "Error: Division by zero" << endl;
errorCheck = 1;
}
if(errorCheck == 0)
{
stack.print();
}
}
int main()
{
cout << "::::::::::::::::RPN CALCULATOR:::::::::::::::::" << endl;
cout << "::TYPE IN A POSTFIX EXPRESSION OR 'q' TO QUIT::" << endl;
cout << ":::::::::::::::::::::::::::::::::::::::::::::::" << endl << endl;
string input;
SLLNode stack;
while(true)
{
cin >> input;
double num;
if(istringstream(input) >> num)
{
stack.pushVal(num);
}
else if (isOperator(input))
{
performOp(input, stack);
}
else if (input == "q")
{
return 0;
}
}
}
The basic idea is to:
Read one line (std::getline);
Process this line (std::stringstream);
Output the answer or any errors;
Clean the stack (or destroy it and create a new one on step 2);
Go to 1 and repeat.
What you are missing is the first step. If you get everything directly from stdin, you will treat the newline as a simple whitespace.
i have to define a variable that i am using in a program but i want the variable to change from int to char.
example
#include <iostream>
#include <cstdlib>
int main()
{
int l=rand();
char x;
std::cout<<"this program makes a random char or number enter n for a number or c if you want a letter\n";
std::cin>>l>>"\n";
if (x="c")
{
char l=rand();
std::cout<<"here is your letter :"<<l<<"\n";
}
else if (x="n")
{
int l=rand();
std::cout<<"here is your number :"<<l<<"\n";
}
}
so i already know there is other problems this was just an example i wrote real quick to show what i meant. i want to make it so that depending on what the user enters it will change l from a char to an int. I don't know if there is something to do this but if there is i would like to know.
Thank You
You can use a union
union char_and_int {
char char_l;
int int_l;
}l;
//...
l.int_l=rand();
if (x == 'c')
{
std::cout<<"here is your letter :"<<l.char_l<<"\n";
}
else if (x == 'n')
{
std::cout<<"here is your number :"<<l.int_l<<"\n";
}
Also, be aware that this can result in unprintable chars
The generic name for this kind of thing is a union.
You can use the union keyword to define a C-style union: a variable which may be treated as having one of several types. However, you need to do all the work to keep track of which type it is.
union {
char c;
int i;
} l;
bool l_is_int;
if ( x == 'c' ) {
l_is_int = false;
cin >> l.i;
} else if ( x == 'n' ) {
l_is_int = true;
cin >> l.c;
}
There is a class boost::variant which does this more elegantly and safely:
boost::variant< char, int > l;
if ( x == 'c' ) {
char c;
cin >> c;
l = c; // set content type of l to char
cout << "your char is " << boost::get< char >( l ) << endl;
} else {
int i;
cin >> i;
l = i; // set content type of l to int
cout << "your int is " << boost::get< int >( l ) << endl;
}
cout << "your int or char is " << l << endl;
For your immediate problem, using any kind of union is overkill, since an int can hold any char value:
int l;
bool l_is_int;
if ( x == 'c' ) {
char c;
cin >> c;
l = c;
l_is_int = false;
} else if ( x == 'n' ) {
cin >> l;
l_is_int = true;
}
Because C++ is a statically-typed language, a variable can't actually change from one type to another. A work around solution would be to create a struct or class that contains both an int and a char variable, and assign them accordingly.
A dynamically-typed language, like Python or Ruby, could do this though.
i am not a pro at c++ but i guess you can declare 2 variables, one char and one int. First you can assign the users input to char, than test it if it can be assigned as integer, and if it can be, than your program will start using that. And for deciding which variable to use, you can also declare another boolean value to keep that data. I believe there must be better ways, but i guess this works too.
I'm doing a polynomial calculator and i'll need some help as i'll progress with the code.
For now I made only the polinom class which i represented it as a linked list with terms and some functions(only read and print the polynomial functions for now).
Here's the main program which for now only read a polynomial and prints it:
#include "polinom.h"
int main()
{
polinom P1;
bool varStatus = false;
char var = '\0', readStatus = '\0';
cout << "P1 = ";
P1.read(readStatus, var, varStatus); // i don't need readStatus yet as i haven't implemented the reset and quit functions
cout << "\n\nP = ";
P1.print(var);
getch();
return 0;
}
And the header file polinom.h:
#ifndef _polinom_h
#define _polinom_h
#include <iostream>
#include <list>
#include <cstdlib>
#include <cctype>
#include <cstdio>
#include <conio.h>
using namespace std;
class polinom
{
class term
{
public:
int coef;
int pow;
term()
{
coef = 1;
pow = 0;
}
};
list<term> poly;
list<term>::iterator i;
public:
bool printable(char c)
{
return (
((int(c) > 42 && int(c) < 123) || isspace(c)) && int(c) != 44 && int(c) != 46 && int(c) != 47 &&
int(c) != 58 && int(c) != 59 &&
int(c) != 60 && int(c) != 61 && int(c) != 62 && int(c) != 63 && int(c) != 64 && int(c) != 65 &&
int(c) != 91 && int(c) != 92 && int(c) != 93 && int(c) != 95 && int(c) != 96
);
}
void read(char &readStatus, char &var, bool &varStatus)
{
term t; // term variable to push it into the list of terms
char c, lc, sign; // c = current char, lc = lastchar and sign the '+' or '-' sign before a coefficient
int coef, pow; //variables to pass the coef and power to term t
bool coefRead = false, powRead = false; //reading status of coef and power
while (c != '\r') { //we read characters until carriage return
c = getch(); // get the new imputed char
if (tolower(c) == 'r' || tolower(c) == 'q') { //if the user inputed r or q we reset the input or quit the program
readStatus = c; //pass current char value to readStatus so the program will know what to do next
return; //aborting the reading process
}
else
{
if (printable(c)) cout << c; //print on screen only the correct characters
if (!coefRead && !powRead) //we set term coef to the inputed value
{
if (isdigit(c)) {
if (isdigit(lc)) coef = coef * 10 + int(c); //if the last char was also a digit we multiply the last value of coef by 10 and add current char
else {
if (sign == '-') coef = -(int(c));//if the current coef has '-' before we set coef to it's negative value
else coef = int(c); //this means a new term's coef is read
}
if (!isdigit(c) && isdigit(lc)) coefRead = true; //if the last char was a digit and we reached the var name we stop reading the coefficient
}
else if (coefRead && !powRead) //after coefficient is read we get the term's varname and power
{
if (isdigit(c)) { // just like in the case with coefficient we read the power until the current char is not a digit
if (isdigit(lc)) pow = pow * 10 + int(c);
else pow = int(c);
}
else if (isalpha(c) && isdigit(lc) && !varStatus) { //if the last char was a digit and the current not we reached the var name
var = c; //also even though the variable is inputed more than once we save it only once
varStatus = true; //we mark the var name as read
}
else {
if (isdigit(lc)) powRead = true;
}
}
else {
if (c == '+' || c == '-') { // if a sign was inputed it means a new term is coming and we push the current term to the list and reset
t.coef = coef; // coefRead and powRead so we can read another term
t.pow = pow;
poly.push_back(t);
sign = c;
coefRead = false;
powRead = false;
}
}
lc = c; // we save the last character
}
}
}
void print(char var)
{
for ( i=poly.begin() ; i != poly.end(); i++ ) { //going through the entire list to retrieve the terms and print them
if (i == poly.end() - 1) { // if we reached the last term
if (*(i->pow == 0) //if the last term's power is 0 we print only it's coefficient
cout << *(i->coef);
else
cout << *(i->coef) << var << "^" << *(i->pow); //otherwise we print both
}
else {
if (*(i->coef > 0) //if the coef value is positive
cout << *(i->coef) << var << "^" << *(i->pow) << " + "; //we also add the '+' sign
else
cout << *(i->coef) << var << "^" << *(i->pow) << " - "; // otherwise we add '-' sign
}
}
}
};
#endif
EDIT
All compile errors fixed now thanks to JonH, but the read function is not working as the input characters aren't correctly inserted into the list. I know it may be trivial for you guys, but it would be great if you help me out.
Thanks!
I found MANY missing curly braces and closing parens all throughout your code. After having spent several minutes fixing at least 10 of these, I thought you would be better served if I helped you to learn to fish, rather than giving you fish for tonight's dinner.
Your code is written like a stream of consciousness. As you are building your code your mind jumps around, thinking of other things you need to build and new requirements introduced by whatever you just wrote. When you think of these things, you go write them and come back to where you were. Before you know it, you have written hundreds of lines of code by jumping around, writing bits here and there. The problem with this is that you can't possibly keep juggling sections of code like this without missing little syntax bits along the way.
You should take a more iterative approach to writing code. How exactly you do this will come with experience, but here's some guidance:
Start by stubbing out a class declaration with a few (preferably 1) core methods and member variables.
Compile. You'll get linker errors and the like, but you shouldn't get any syntax errors like missing parens or semicolons. Fix any you do find before moving on.
Implement the methods/functions you just stubbed. Compile & fix non-linker errors.
As you think of minor or dependant requirements that came up during the above steps, write comments in your code, like // TODO: Implement bool DoTheThing(int); But don't implement them yet.
Loop back to step 1, keeping the scope of what you're working on as limited and fundamental as possible. Never move beyond a compilation step without a clean compile.
Repeat until you have implemented everything. You might compile 50 times or more during this process.
Your fundamental problem is that you wrote a bunch of code down without testing it piece by piece, without thinking about it. When you write as a beginner, you should try adding one little bit at a time and making sure it compiles. Even as an advanced programmer, modularization is an extremely important part of the design and code-writing process.
That said, here are a few tips about your posted code in particular:
Your function printable is ugly as sin, and therefore impossible to debug or understand.
The number of nested if statements is indicative of design flaws.
You're missing an end brace on your if (isdigit(c)) statement.
Declaring (and especially initializing) multiple variables on the same line is bad form.
Those compile errors surely has a line number associated to them in the error message. Have you tried looking at the line indicated to see what is missing? If that does not help, please post the complete error output from the compiler so that we can se what the error is.
You are missing a few curly braces in your read function.
I redid it here:
void read(char &readStatus, char &var, bool &varStatus)
{
term t; // term variable to push it into the list of terms
char c, lc, sign; // c = current char, lc = lastchar and sign the '+' or '-' sign before a coefficient
int coef, pow; //variables to pass the coef and power to term t
bool coefRead = false, powRead = false; //reading status of coef and power
while (c != '\r') { //we read characters until carriage return
c = getch(); // get the new imputed char
if (tolower(c) == 'r' || tolower(c) == 'q')
{ //if the user inputed r or q we reset the input or quit the program
readStatus = c; //pass current char value to readStatus so the program will know what to do next
return; //aborting the reading process
}
else
{
if (printable(c))
cout << c; //print on screen only the correct characters
if (!coefRead && !powRead) //we set term coef to the inputed value
{
if (isdigit(c))
{
if (isdigit(lc))
coef = coef * 10 + int(c); //if the last char was also a digit we multiply the last value of coef by 10 and add current char
else
{
if (sign == '-')
coef = -(int(c));//if the current coef has '-' before we set coef to it's negative value
else
coef = int(c); //this means a new term's coef is read
} //end else
}//end if isdigit(c)
if (!isdigit(c) && isdigit(lc))
coefRead = true; //if the last char was a digit and we reached the var name we stop reading the coefficient
} //end if
else if (coefRead && !powRead) //after coefficient is read we get the term's varname and power
{
if (isdigit(c))
{ // just like in the case with coefficient we read the power until the current char is not a digit
if (isdigit(lc))
pow = pow * 10 + int(c);
else
pow = int(c);
}
else if (isalpha(c) && isdigit(lc) && !varStatus)
{ //if the last char was a digit and the current not we reached the var name
var = c; //also even though the variable is inputed more than once we save it only once
varStatus = true; //we mark the var name as read
}
else
{
if (isdigit(lc))
powRead = true;
}
} //end else if
else
{
if (c == '+' || c == '-')
{ // if a sign was inputed it means a new term is coming and we push the current term to the list and reset
t.coef = coef; // coefRead and powRead so we can read another term
t.pow = pow;
poly.push_back(t);
sign = c;
coefRead = false;
powRead = false;
}
}
lc = c; // we save the last character
} //end else
} //end while
} //end function
EDIT
I also fixed the print function:
void print(char var)
{
for ( i=poly.begin() ; i != poly.end(); i++ ) { //going through the entire list to retrieve the terms and print them
if (i == poly.end()) { // if we reached the last term
if (i->pow == 0) //if the last term's power is 0 we print only it's coefficient
cout << i->coef;
else
cout << i->coef << var << "^" << i->pow; //otherwise we print both
}
else {
if (i->coef > 0) //if the coef value is positive
cout << i->coef << var << "^" << i->pow << " + "; //we also add the '+' sign
else
cout << i->coef << var << "^" << i->pow << " - "; // otherwise we add '-' sign
}
}
}