What's wrong with my ternary `if` expression? - c++

i understand that the conditional operator ? can be used to simplify the if conditional but i'm really having a hard time with it, is it possible to use it as a loop ? for example in the code here it keeps telling me that i can not use r as a function what exactly am i missing ?
#include <iostream>
using namespace std;
#define PI 3.14159
int main () {
double r,circle,o;
int rmax =0;
int n;
cout << "enter the number of circles:";
cin >> n;
(n > 1) ? cin >> r (r > rmax) ? rmax = r : r=r: cout<<rmax;
}

The ternary operator (?:) can be easier described using a function:
#include <iostream>
template<typename T>
T &ternary(bool a, T &b, T &c) {
if (a)
return b;
else
return c;
}
int main() {
// The behavior is not completely equivalent
// This example just explains the basic concept of the ternary operator
std::cout << ternary(true, 5, 2) << '\n';
std::cout << (true ? 5 : 2) << '\n';
}
The expression condition ? value1 : value2 returns either value1 or value2 depending on condition.
Of course, value1 and value2 can also be complex expressions but you have to remember to handle the returned values.
#include <iostream>
int main() {
int a;
std::cout << (true ? a = 5 : 2) << '\n';
}
Both possible values must have the same type.
Your expression would look like:
ternary((n > 1), cin >> r ternary((r > rmax), rmax = r, r=r), cout<<rmax);
Now the problem should be obvious.

Related

This code throws an error at line 6. Is it because cout stream doesn't allow it or it's some conflict in ostream?

#include<iostream>
using namespace std;
int main() {
int a=4,b;
cout<<b=a*a;
return 0;
}
it shows
"error: no match for 'operator=' (operand types are 'std::basic_ostream<char>' and 'char')"
If it has to do something with cout, can someone tell me how does cin and cout works exactly?
See here for operator precedence: https://en.cppreference.com/w/cpp/language/operator_precedence.
<< has rank 7. = has rank 16. And * has rank 5. Hence the line is parsed as
(std::cout << b ) = (a * a);
You cannot assign an int to std::cout. Write this instead:
int a = 4;
int b = a*a;
std::cout << b;

Printing all palindrome numbers in a given range

I'm trying to write a program that would print all palindrome in range [a, b]. I've written this so far, but nothing is printed after I input the values for a, b. What is missing?
#include "stdafx.h"
#include <iostream>
using namespace std;
int t = 0, rmd, z, a, b;
int reverse() {
while (z != 0) {
rmd = z% 10;
t = t * 10 + rmd;
z/= 10;
}
return t;
}
int palin() {
if (a == reverse()) {
return 1;
}
else
return 0;
}
int main() {
cout << "a: "; cin >> a;
cout << "b: "; cin >> b;
while (a <= b) {
z = a;
if (palin())
cout << a << endl;
a++;
}
system("pause");
return 0;
}
The problem is that the variable t is not local to your reverse() function. Its value survives to the following invocation, so the result of reverse becomes junk unrelated to the actual call.
You need to make t local to reverse() in order to fix this problem.
In general, it is a good idea to develop a habit of declaring your variables in the innermost scope to which they could belong without breaking your code. In this case, this would be the scope of reverse() function for t, and the scope of main for the remaining variables; palin should take a as its parameter.
Your use of variables is what is confusing you. The actual issue is not setting t to zero every time you call reverse, but you should think about how you use variable scoping and what functions actually do. Right now you have 2 procedures, that perform actions on global data. Instead try to formulate the problem using functions that accept arguments, and return a result.
#include <iostream>
using namespace std;
int reverse(int z) {
int t = 0;
int rmd;
while (z != 0) {
rmd = z % 10;
t = t * 10 + rmd;
z/= 10;
}
return t;
}
int palin(int z) {
return z == reverse(z);
}
int main() {
int a, b;
cout << "a: "; cin >> a;
cout << "b: "; cin >> b;
while (a <= b) {
if (palin(a)) {
cout << a << endl;
}
a++;
}
system("pause");
return 0;
}

Access to the struct elements. Is it possible to access like a vector?

I have the following example (simplified) using a struct:
#include <iostream>
#include <algorithm>
#include <time.h>
using namespace std;
struct s_str
{
int a=1,b=2,c=3;
};
int main(void)
{
s_str str;
int sel;
srand(time(NULL)); //initialize random seed
sel = rand() % (3); //generate a random number between 0 and 2
cout << "sel: " << sel << endl;
cout << "str: " << str.??? << endl;//I was wondering to output a, b or c
return 0; //depending whether sel=0,1,2respectively.
}
When the struct "str" is defined, we can access to each element by using the opertor "." followed by the name of the element. For instance "str.c" will give us the number 3.
However in this example we don't know the element of "str" to output when programing because it's randomly selected by sel.
I don't know how to output "str.???" from sel number, that is, str.a if sel=0, str.b if sel=1, and str.c if sel=3.
I tried something like "str.[sel]", but it didn't work. Can you help me?
PD: I don't want to bother too much, but how to solve the same problem but now supposing that a,b and c have different variable type. For example:
int a=1,b=2;
string c="hola";
I tried to do it with two operators, but it didn't compile because they were overloaded.
As mentioned you can't do this without providing a certain mapping and indexing operator. The following should work well:
struct s_str
{
int a=1,b=2,c=3;
int& operator[](int index) {
switch(index) {
case 0:
return a;
case 1:
return b;
case 2:
return c;
default:
throw std::out_of_range("s_str: Index out of range.");
break;
}
}
};
int main() {
s_str s;
cout << s[0] << ", " << s[1] << ", " << s[2] << endl;
// cout << s[42] << endl; // Uncomment to see it fail.
return 0;
}
In general, no.
If the only distinguishing feature of the elements of the struct is their index, define a vector or array in the struct.
If you sometimes want to refer to the elements by name and sometimes by position, define an operator []( int ) for the struct.
Te easiest way, if you have only a couple of ints in your structure is:
struct s_str
{
int a = 1, b = 2, c = 3;
int& operator[] (size_t t) {
assert(t<3); // assumption for the following to return a meaningful value
return (t == 0 ? a : (t == 1 ? b : c));
}
};
You'd access with
cout << "str: " << str[sel] << endl;
and you could even use int to assign, because it's by reference:
str[sel] = 9;
cout << "a,b,c=" << str.a << "," << str.b << "," << str.c << endl;

C++: Converting Hexadecimal to Decimal

I'm looking for a way to convert hex(hexadecimal) to dec(decimal) easily. I found an easy way to do this like :
int k = 0x265;
cout << k << endl;
But with that I can't input 265. Is there anyway for it to work like that:
Input: 265
Output: 613
Is there anyway to do that ?
Note: I've tried:
int k = 0x, b;
cin >> b;
cout << k + b << endl;
and it doesn't work.
#include <iostream>
#include <iomanip>
#include <sstream>
int main()
{
int x, y;
std::stringstream stream;
std::cin >> x;
stream << x;
stream >> std::hex >> y;
std::cout << y;
return 0;
}
Use std::hex manipulator:
#include <iostream>
#include <iomanip>
int main()
{
int x;
std::cin >> std::hex >> x;
std::cout << x << std::endl;
return 0;
}
Well, the C way might be something like ...
#include <stdlib.h>
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
printf("%X", n);
exit(0);
}
Here is a solution using strings and converting it to decimal with ASCII tables:
#include <iostream>
#include <string>
#include "math.h"
using namespace std;
unsigned long hex2dec(string hex)
{
unsigned long result = 0;
for (int i=0; i<hex.length(); i++) {
if (hex[i]>=48 && hex[i]<=57)
{
result += (hex[i]-48)*pow(16,hex.length()-i-1);
} else if (hex[i]>=65 && hex[i]<=70) {
result += (hex[i]-55)*pow(16,hex.length( )-i-1);
} else if (hex[i]>=97 && hex[i]<=102) {
result += (hex[i]-87)*pow(16,hex.length()-i-1);
}
}
return result;
}
int main(int argc, const char * argv[]) {
string hex_str;
cin >> hex_str;
cout << hex2dec(hex_str) << endl;
return 0;
}
I use this:
template <typename T>
bool fromHex(const std::string& hexValue, T& result)
{
std::stringstream ss;
ss << std::hex << hexValue;
ss >> result;
return !ss.fail();
}
std::cout << "Enter decimal number: " ;
std::cin >> input ;
std::cout << "0x" << std::hex << input << '\n' ;
if your adding a input that can be a boolean or float or int it will be passed back in the int main function call...
With function templates, based on argument types, C generates separate functions to handle each type of call appropriately. All function template definitions begin with the keyword template followed by arguments enclosed in angle brackets < and >. A single formal parameter T is used for the type of data to be tested.
Consider the following program where the user is asked to enter an integer and then a float, each uses the square function to determine the square.
With function templates, based on argument types, C generates separate functions to handle each type of call appropriately. All function template definitions begin with the keyword template followed by arguments enclosed in angle brackets < and >. A single formal parameter T is used for the type of data to be tested.
Consider the following program where the user is asked to enter an integer and then a float, each uses the square function to determine the square.
#include <iostream>
using namespace std;
template <class T> // function template
T square(T); /* returns a value of type T and accepts type T (int or float or whatever) */
void main()
{
int x, y;
float w, z;
cout << "Enter a integer: ";
cin >> x;
y = square(x);
cout << "The square of that number is: " << y << endl;
cout << "Enter a float: ";
cin >> w;
z = square(w);
cout << "The square of that number is: " << z << endl;
}
template <class T> // function template
T square(T u) //accepts a parameter u of type T (int or float)
{
return u * u;
}
Here is the output:
Enter a integer: 5
The square of that number is: 25
Enter a float: 5.3
The square of that number is: 28.09
This should work as well.
#include <ctype.h>
#include <string.h>
template<typename T = unsigned int>
T Hex2Int(const char* const Hexstr, bool* Overflow)
{
if (!Hexstr)
return false;
if (Overflow)
*Overflow = false;
auto between = [](char val, char c1, char c2) { return val >= c1 && val <= c2; };
size_t len = strlen(Hexstr);
T result = 0;
for (size_t i = 0, offset = sizeof(T) << 3; i < len && (int)offset > 0; i++)
{
if (between(Hexstr[i], '0', '9'))
result = result << 4 ^ Hexstr[i] - '0';
else if (between(tolower(Hexstr[i]), 'a', 'f'))
result = result << 4 ^ tolower(Hexstr[i]) - ('a' - 10); // Remove the decimal part;
offset -= 4;
}
if (((len + ((len % 2) != 0)) << 2) > (sizeof(T) << 3) && Overflow)
*Overflow = true;
return result;
}
The 'Overflow' parameter is optional, so you can leave it NULL.
Example:
auto result = Hex2Int("C0ffee", NULL);
auto result2 = Hex2Int<long>("DeadC0ffe", NULL);
only use:
cout << dec << 0x;
If you have a hexadecimal string, you can also use the following to convert to decimal
int base = 16;
std::string numberString = "0xa";
char *end;
long long int number;
number = strtoll(numberString.c_str(), &end, base);
I think this is much cleaner and it also works with your exception.
#include <iostream>
using namespace std;
using ll = long long;
int main ()
{
ll int x;
cin >> hex >> x;
cout << x;
}
std::stoi, stol, stoul, stoull can convert to different number systems
long long hex2dec(std::string hex)
{
std::string::size_type sz = 0;
try
{
hex = "0x"s + hex;
return std::stoll(hex, &sz, 16);
}
catch (...)
{
return 0;
}
}
and similar if you need return string
std::string hex2decstr(std::string hex)
{
std::string::size_type sz = 0;
try
{
hex = "0x"s + hex;
return std::to_string(std::stoull(hex, &sz, 16));
}
catch (...)
{
return "";
}
}
Usage:
std::string converted = hex2decstr("16B564");

Where can I find some simple code examples of recursion in C++?

I am completely newbie to C++. I am doing a practice which consists of building a very simple C++ program.
My teacher emphasizes that it must use recursion with functions and methods. I am wondering how to use recursion within a method in C++. I was looking for some code examples but I haven't find anything. My deep concerns are how a method calls itself without not knowing the name of its class/instance.
class Foo
{
public:
Foo(int offset) : offset(offset) {}
int bar(int x)
{
if (x == 0)
{
return offset; // Base-case
}
return x + bar(x-1); // Recursion
}
private:
int offset;
};
int main()
{
Foo foo(7);
std::cout << foo.bar(5) << "\n"; Prints "22" (5+4+3+2+1+7)
}
Wikipedia: Recursion
I guess your homework is to write a Recursive Descent Parser. A simple example in C:
uBASIC
An example:
#include <iostream>
using namespace std;
int factorial(int n) // 1, 1, 2, 6, 24, 120, 720, ...
{
if (n == 0) return 1;
return n * factorial(n-1);
}
main()
{
int n = 7;
cout << "Enter a non-negative integer: ";
cin >> n;
cout << "The Factorial of " << n << " is " << factorial(n) << endl;
return 0;
}
You can find more examples here : http://www.cstutoringcenter.com/tutorials/cpp/cpp6.php