How can I take char value with int? - c++

How can I take char value with int value?
For example I want enter + because I'm making a calculator program:
#include <iostream>
int main() {
int a;
std::cin >> a;
std::cout << a;
return 0;
}

you can see the value of int into char by static casting your int to char.
std::cout << static_cast<char>(a);

Related

Deleting characters in a char array

#include <iostream>
#include <string.h>
#include <algorithm>
# define N 100
using namespace std;
int main()
{
char A[N];
unsigned char APP[256] = {0};
cout << "Insert string" << endl;
cin.getline(A,100);
for(int i=0; i < strlen(A); ++i)
{
unsigned char B = A[i];
if(!APP[B])
{
++APP[B];
cout << B;
}
}
return 0;
}
/*char eliminazione(char,char)
{
}*/`
I have to put the for in the "delete" function calling the value B and print it in main, do you know how to do it?
Given a string A read from the keyboard, create a function in C ++ language that calculates a second string B obtained from the first by deleting all the characters that appear more than once. The resulting string must therefore contain the characters of the first string, in the same order, but without repetitions.
Instead of 'cout', you just store the characters into a new string, and increment its index, see code below as an example:
#include <iostream>
#include <string.h>
#include <algorithm>
# define N 100
using namespace std;
int main()
{
unsigned char A[N]; // better to have same type for both A and B
unsigned char B[N];
memset(B, 0, sizeof(B));
unsigned char APP[256] = {0};
cout << "Insert string" << endl;
cin.getline(A,100);
int j = 0;
for(int i=0; i < strlen(A); ++i)
{
unsigned char c = A[i];
if(!APP[c]++)
B[j++] = c; //cout << c;
}
cout << B << endl;
return 0;
}
Output:
Insert string
lalalgdgdfsgwwyrtytr
lagdfswyrt

istringstream-function string_to_int cannot take c-str, why?

I learned a helper function that can convert strings to integers:
int string_to_int(string s)
{
istringstream instr(s);
int n;
instr>>n;
return n;
}
It's mentioned that the argument s cannot be c-str string, why is this the case?
But you can pass a C style string.
The reason for that is because the std::string constructor can implicitly accept a CharT* (Char type, which is char in this case) as a parameter. Thus, something like the following would work:
#include <iostream>
#include <sstream>
using namespace std;
int string_to_int(string s)
{
istringstream instr(s);
int n;
instr>>n;
return n;
}
int main()
{
const char* test = "12345";
std::cout << string_to_int(test) << "\n"; // Outputs 12345
std::cout << string_to_int("122") << "\n"; // Outputs 122
}

C++ function overloading cannot identify char

When I input two integers, the output is correctly their difference. However when I enter a string and a char, instead of returning how many times the char appears in the string, it returns -1, which is the out put for error. Could anyone please help me? It's just my second day learing c++...
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
void mycount(int a, int b)
{
std::cout<< a - b <<std::endl;
}
void mycount(char str[], char s[])
{
int len,i;
int sum=0;
len = strlen(str);
for (i=0;i<len;i++){
if (strncmp(&str[i],&s[0],1) == 0){
sum = sum + 1;
};
};
printf("results: %d times\n",sum);
}
int main()
{
int a,b;
char c[200],d;
if(std::cin>> a >> b){
mycount(a,b);
}
if(std::cin>> c[200] >> d){
mycount(a,b);
}
else{
std::cout<< "-1" <<std::endl;
}
std::cin.clear();
std::cin.sync();
}
Hint - what will this program print?
#include <iostream>
using namespace std;
int main()
{
char c[200],d;
cout << sizeof(c) << endl;
cout << sizeof(d) << endl;
return 0;
}
Answer:
200
1
That declaration does not do what you think it does - c is an array of 200 chars, d is a single char. It's a feature of the C declaration syntax, same as:
int *c, d;
c is a pointer to int, d is an int.
Since you are doing C++, why not make your life easier and use std::string instead?
A few changes should fix your problems. First when inputting an array with cin use getline and call ignore right before hand. I find it easier to pass s as a char instead of an array of size one make sure your call your second my count with c and d instead of a and b.
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
void mycount(int a, int b)
{
std::cout<< a - b <<std::endl;
}
void mycount(char str[], char s)
{
int len,i;
int sum=0;
len = strlen(str);
for (i=0;i<len;i++){
if (strncmp(&str[i],&s,1) == 0){
sum = sum + 1;
};
};
printf("results: %d times\n",sum);
}
int main()
{
int a,b;
char c[200],d;
if(std::cin>> a >> b){
mycount(a,b);
}
std::cin.ignore();
if(std::cin.getline (c,200) && std::cin >> d){
mycount(c,d);
}
else{
std::cout<< "-1" <<std::endl;
}
std::cin.clear();
std::cin.sync();
}
These changes should fix it.

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");

converting from strings to ints

I would like to know what is the easiest way to convert an int to C++ style string and from C++ style string to int.
edit
Thank you very much. When converting form string to int what happens if I pass a char string ? (ex: "abce").
Thanks & Regards,
Mousey
Probably the easiest is to use operator<< and operator>> with a stringstream (you can initialize a stringstream from a string, and use the stream's .str() member to retrieve a string after writing to it.
Boost has a lexical_cast that makes this particularly easy (though hardly a paragon of efficiency). Normal use would be something like int x = lexical_cast<int>(your_string);
You can change "%x" specifier to "%d" or any other format supported by sprintf. Ensure to appropriately adjust the buffer size 'buf'
int main(){
char buf[sizeof(int)*2 + 1];
int x = 0x12345678;
sprintf(buf, "%x", x);
string str(buf);
int y = atoi(str.c_str());
}
EDIT 2:
int main(){
char buf[sizeof(int)*2 + 1];
int x = 42;
sprintf(buf, "%x", x);
string str(buf);
//int y = atoi(str.c_str());
int y = static_cast<int>(strtol(str.c_str(), NULL, 16));
}
This is to convert string to number.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
int convert_string_to_number(const std::string& st)
{
std::istringstream stringinfo(st);
int num = 0;
stringinfo >> num;
return num;
}
int main()
{
int number = 0;
std::string number_as_string("425");
number = convert_string_to_number(number_as_string);
std::cout << "The number is " << number << std::endl;
std::cout << "Number of digits are " << number_as_string.length() << std::endl;
}
Like wise, the following is to convert number to string.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
std::string convert_number_to_string(const int& number_to_convert)
{
std::ostringstream os;
os << number_to_convert;
return (os.str());
}
int main()
{
int number = 425;
std::string stringafterconversion;
stringafterconversion = convert_number_to_string(number);
std::cout << "After conversion " << stringafterconversion << std::endl;
std::cout << "Number of digits are " << stringafterconversion.length() << std::endl;
}
Use atoi to convert a string to an int. Use a stringstream to convert the other way.