C++: Constant Reference Parameters - c++

why do we use Constant Reference Parameters in this code
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
// Converts a hex number as a string to decimal
int hex2Dec(const string& hex); // here why we use reference and const it seems we do not change hex in the function body
// Converts a hex character to a decimal value
int hexCharToDecimal(char ch);
int main()
{
// Prompt the user to enter a hex number as a string
cout << "Enter a hex number: ";
string hex;
cin >> hex;
cout << "The decimal value for hex number " << hex
<< " is " << hex2Dec(hex) << endl;
return 0;
}
int hex2Dec(const string& hex)
{
int decimalValue = 0;
for (unsigned i = 0; i < hex.size(); i++)
decimalValue = decimalValue * 16 + hexCharToDecimal(hex[i]);
return decimalValue;
}
int hexCharToDecimal(char ch)
{
ch = toupper(ch); // Change it to uppercase
if (ch >= 'A' && ch <= 'F')
return 10 + ch - 'A';
else // ch is '0', '1', ..., or '9'
return ch - '0';
}
what is the use of calling by reference in this problem ?
in this segment of code
int hex2Dec(const string& hex)
{
int decimalValue = 0;
for (unsigned i = 0; i < hex.size(); i++)
decimalValue = decimalValue * 16 + hexCharToDecimal(hex[i]);
return decimalValue;
}
we do not change the hex.
what is the purpose of const reference in this example and in genral?

The naive solution is to use int hex2Dec(string hex) here. However because function arguments are copied in C++ calling this function would cause a new string to be created for hex, copied from the function argument every time hex2Dec is called. This can lead to needless performance issues, specially if the strings are large.
The solution to this problem is to pass the argument by reference. Using int hex2Dec(string & hex) fixes the first problem, now calling the function never causes a new string to be created. It always refer to whatever string was given.
This introduces a new problem. First, because the argument is a reference, it's possible for the function to change the argument. Because we can see the function implementation, we know it doesn't. But anyone trying to use that function can't know that. Second, because of this, it is not possible to call the function with a const string. The compiler knows it is forbidden to change a const string and it sees that the function doesn't promise not to change it so it will produce an error if you try it. This is very limiting, for example it wouldn't be possible to call the function with a string literal (ex. hex2Dec("test")).
#include <string>
int hex2Dec(std::string& hex);
int main()
{
std::string foo = "foo";
const std::string bar = "bar";
hex2Dec(foo); // Okay
//hex2Dec(bar); Compilation Error
//hex2Dec("baz"); Compilation Error
}
The solution to this new problem is to add const to the argument type : int hex2Dec(const string & hex). The const means that this reference can never be used to modify the argument. Now, users of the function and the compiler both know its safe to use the function with const strings, and the calling the function never copies the argument.
#include <string>
int hex2Dec(const std::string& hex);
int main()
{
std::string foo = "foo";
const std::string bar = "bar";
hex2Dec(foo); // Okay
hex2Dec(bar); // Okay
hex2Dec("baz"); // Okay
}

Related

C++: Convert CONTENT of String to char [duplicate]

I want to convert a hex string to a 32 bit signed integer in C++.
So, for example, I have the hex string "fffefffe". The binary representation of this is 11111111111111101111111111111110. The signed integer representation of this is: -65538.
How do I do this conversion in C++? This also needs to work for non-negative numbers. For example, the hex string "0000000A", which is 00000000000000000000000000001010 in binary, and 10 in decimal.
use std::stringstream
unsigned int x;
std::stringstream ss;
ss << std::hex << "fffefffe";
ss >> x;
the following example produces -65538 as its result:
#include <sstream>
#include <iostream>
int main() {
unsigned int x;
std::stringstream ss;
ss << std::hex << "fffefffe";
ss >> x;
// output it as a signed type
std::cout << static_cast<int>(x) << std::endl;
}
In the new C++11 standard, there are a few new utility functions which you can make use of! specifically, there is a family of "string to number" functions (http://en.cppreference.com/w/cpp/string/basic_string/stol and http://en.cppreference.com/w/cpp/string/basic_string/stoul). These are essentially thin wrappers around C's string to number conversion functions, but know how to deal with a std::string
So, the simplest answer for newer code would probably look like this:
std::string s = "0xfffefffe";
unsigned int x = std::stoul(s, nullptr, 16);
NOTE: Below is my original answer, which as the edit says is not a complete answer. For a functional solution, stick the code above the line :-).
It appears that since lexical_cast<> is defined to have stream conversion semantics. Sadly, streams don't understand the "0x" notation. So both the boost::lexical_cast and my hand rolled one don't deal well with hex strings. The above solution which manually sets the input stream to hex will handle it just fine.
Boost has some stuff to do this as well, which has some nice error checking capabilities as well. You can use it like this:
try {
unsigned int x = lexical_cast<int>("0x0badc0de");
} catch(bad_lexical_cast &) {
// whatever you want to do...
}
If you don't feel like using boost, here's a light version of lexical cast which does no error checking:
template<typename T2, typename T1>
inline T2 lexical_cast(const T1 &in) {
T2 out;
std::stringstream ss;
ss << in;
ss >> out;
return out;
}
which you can use like this:
// though this needs the 0x prefix so it knows it is hex
unsigned int x = lexical_cast<unsigned int>("0xdeadbeef");
For a method that works with both C and C++, you might want to consider using the standard library function strtol().
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
string s = "abcd";
char * p;
long n = strtol( s.c_str(), & p, 16 );
if ( * p != 0 ) { //my bad edit was here
cout << "not a number" << endl;
}
else {
cout << n << endl;
}
}
Andy Buchanan, as far as sticking to C++ goes, I liked yours, but I have a few mods:
template <typename ElemT>
struct HexTo {
ElemT value;
operator ElemT() const {return value;}
friend std::istream& operator>>(std::istream& in, HexTo& out) {
in >> std::hex >> out.value;
return in;
}
};
Used like
uint32_t value = boost::lexical_cast<HexTo<uint32_t> >("0x2a");
That way you don't need one impl per int type.
Working example with strtoul will be:
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
string s = "fffefffe";
char * p;
long n = strtoul( s.c_str(), & p, 16 );
if ( * p != 0 ) {
cout << "not a number" << endl;
} else {
cout << n << endl;
}
}
strtol converts string to long. On my computer numeric_limits<long>::max() gives 0x7fffffff. Obviously that 0xfffefffe is greater than 0x7fffffff. So strtol returns MAX_LONG instead of wanted value. strtoul converts string to unsigned long that's why no overflow in this case.
Ok, strtol is considering input string not as 32-bit signed integer before convertation. Funny sample with strtol:
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
string s = "-0x10002";
char * p;
long n = strtol( s.c_str(), & p, 16 );
if ( * p != 0 ) {
cout << "not a number" << endl;
} else {
cout << n << endl;
}
}
The code above prints -65538 in console.
Here's a simple and working method I found elsewhere:
string hexString = "7FF";
int hexNumber;
sscanf(hexString.c_str(), "%x", &hexNumber);
Please note that you might prefer using unsigned long integer/long integer, to receive the value.
Another note, the c_str() function just converts the std::string to const char* .
So if you have a const char* ready, just go ahead with using that variable name directly, as shown below [I am also showing the usage of the unsigned long variable for a larger hex number. Do not confuse it with the case of having const char* instead of string]:
const char *hexString = "7FFEA5"; //Just to show the conversion of a bigger hex number
unsigned long hexNumber; //In case your hex number is going to be sufficiently big.
sscanf(hexString, "%x", &hexNumber);
This works just perfectly fine (provided you use appropriate data types per your need).
I had the same problem today, here's how I solved it so I could keep lexical_cast<>
typedef unsigned int uint32;
typedef signed int int32;
class uint32_from_hex // For use with boost::lexical_cast
{
uint32 value;
public:
operator uint32() const { return value; }
friend std::istream& operator>>( std::istream& in, uint32_from_hex& outValue )
{
in >> std::hex >> outValue.value;
}
};
class int32_from_hex // For use with boost::lexical_cast
{
uint32 value;
public:
operator int32() const { return static_cast<int32>( value ); }
friend std::istream& operator>>( std::istream& in, int32_from_hex& outValue )
{
in >> std::hex >> outvalue.value;
}
};
uint32 material0 = lexical_cast<uint32_from_hex>( "0x4ad" );
uint32 material1 = lexical_cast<uint32_from_hex>( "4ad" );
uint32 material2 = lexical_cast<uint32>( "1197" );
int32 materialX = lexical_cast<int32_from_hex>( "0xfffefffe" );
int32 materialY = lexical_cast<int32_from_hex>( "fffefffe" );
// etc...
(Found this page when I was looking for a less sucky way :-)
Cheers,
A.
just use stoi/stol/stoll
for example:
std::cout << std::stol("fffefffe", nullptr, 16) << std::endl;
output: 4294901758
This worked for me:
string string_test = "80123456";
unsigned long x;
signed long val;
std::stringstream ss;
ss << std::hex << string_test;
ss >> x;
// ss >> val; // if I try this val = 0
val = (signed long)x; // However, if I cast the unsigned result I get val = 0x80123456
Try this. This solution is a bit risky. There are no checks. The string must only have hex values and the string length must match the return type size. But no need for extra headers.
char hextob(char ch)
{
if (ch >= '0' && ch <= '9') return ch - '0';
if (ch >= 'A' && ch <= 'F') return ch - 'A' + 10;
if (ch >= 'a' && ch <= 'f') return ch - 'a' + 10;
return 0;
}
template<typename T>
T hextot(char* hex)
{
T value = 0;
for (size_t i = 0; i < sizeof(T)*2; ++i)
value |= hextob(hex[i]) << (8*sizeof(T)-4*(i+1));
return value;
};
Usage:
int main()
{
char str[4] = {'f','f','f','f'};
std::cout << hextot<int16_t>(str) << "\n";
}
Note: the length of the string must be divisible by 2
For those looking to convert number base for unsigned numbers, it is pretty trivial to do yourself in both C/C++ with minimal dependency (only operator not provided by the language itself is pow() function).
In mathematical terms, a positive ordinal number d in base b with n number of digits can be converted to base 10 using:
Example: Converting base 16 number 00f looks like:
= 0*16^2 + 0*16^1 + 16*16^0 = 15
C/C++ Example:
#include <math.h>
unsigned int to_base10(char *d_str, int len, int base)
{
if (len < 1) {
return 0;
}
char d = d_str[0];
// chars 0-9 = 48-57, chars a-f = 97-102
int val = (d > 57) ? d - ('a' - 10) : d - '0';
int result = val * pow(base, (len - 1));
d_str++; // increment pointer
return result + to_base10(d_str, len - 1, base);
}
int main(int argc, char const *argv[])
{
char n[] = "00f"; // base 16 number of len = 3
printf("%d\n", to_base10(n, 3, 16));
}

How to extract hex value from a string in C++ [duplicate]

I want to convert a hex string to a 32 bit signed integer in C++.
So, for example, I have the hex string "fffefffe". The binary representation of this is 11111111111111101111111111111110. The signed integer representation of this is: -65538.
How do I do this conversion in C++? This also needs to work for non-negative numbers. For example, the hex string "0000000A", which is 00000000000000000000000000001010 in binary, and 10 in decimal.
use std::stringstream
unsigned int x;
std::stringstream ss;
ss << std::hex << "fffefffe";
ss >> x;
the following example produces -65538 as its result:
#include <sstream>
#include <iostream>
int main() {
unsigned int x;
std::stringstream ss;
ss << std::hex << "fffefffe";
ss >> x;
// output it as a signed type
std::cout << static_cast<int>(x) << std::endl;
}
In the new C++11 standard, there are a few new utility functions which you can make use of! specifically, there is a family of "string to number" functions (http://en.cppreference.com/w/cpp/string/basic_string/stol and http://en.cppreference.com/w/cpp/string/basic_string/stoul). These are essentially thin wrappers around C's string to number conversion functions, but know how to deal with a std::string
So, the simplest answer for newer code would probably look like this:
std::string s = "0xfffefffe";
unsigned int x = std::stoul(s, nullptr, 16);
NOTE: Below is my original answer, which as the edit says is not a complete answer. For a functional solution, stick the code above the line :-).
It appears that since lexical_cast<> is defined to have stream conversion semantics. Sadly, streams don't understand the "0x" notation. So both the boost::lexical_cast and my hand rolled one don't deal well with hex strings. The above solution which manually sets the input stream to hex will handle it just fine.
Boost has some stuff to do this as well, which has some nice error checking capabilities as well. You can use it like this:
try {
unsigned int x = lexical_cast<int>("0x0badc0de");
} catch(bad_lexical_cast &) {
// whatever you want to do...
}
If you don't feel like using boost, here's a light version of lexical cast which does no error checking:
template<typename T2, typename T1>
inline T2 lexical_cast(const T1 &in) {
T2 out;
std::stringstream ss;
ss << in;
ss >> out;
return out;
}
which you can use like this:
// though this needs the 0x prefix so it knows it is hex
unsigned int x = lexical_cast<unsigned int>("0xdeadbeef");
For a method that works with both C and C++, you might want to consider using the standard library function strtol().
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
string s = "abcd";
char * p;
long n = strtol( s.c_str(), & p, 16 );
if ( * p != 0 ) { //my bad edit was here
cout << "not a number" << endl;
}
else {
cout << n << endl;
}
}
Andy Buchanan, as far as sticking to C++ goes, I liked yours, but I have a few mods:
template <typename ElemT>
struct HexTo {
ElemT value;
operator ElemT() const {return value;}
friend std::istream& operator>>(std::istream& in, HexTo& out) {
in >> std::hex >> out.value;
return in;
}
};
Used like
uint32_t value = boost::lexical_cast<HexTo<uint32_t> >("0x2a");
That way you don't need one impl per int type.
Working example with strtoul will be:
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
string s = "fffefffe";
char * p;
long n = strtoul( s.c_str(), & p, 16 );
if ( * p != 0 ) {
cout << "not a number" << endl;
} else {
cout << n << endl;
}
}
strtol converts string to long. On my computer numeric_limits<long>::max() gives 0x7fffffff. Obviously that 0xfffefffe is greater than 0x7fffffff. So strtol returns MAX_LONG instead of wanted value. strtoul converts string to unsigned long that's why no overflow in this case.
Ok, strtol is considering input string not as 32-bit signed integer before convertation. Funny sample with strtol:
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
string s = "-0x10002";
char * p;
long n = strtol( s.c_str(), & p, 16 );
if ( * p != 0 ) {
cout << "not a number" << endl;
} else {
cout << n << endl;
}
}
The code above prints -65538 in console.
Here's a simple and working method I found elsewhere:
string hexString = "7FF";
int hexNumber;
sscanf(hexString.c_str(), "%x", &hexNumber);
Please note that you might prefer using unsigned long integer/long integer, to receive the value.
Another note, the c_str() function just converts the std::string to const char* .
So if you have a const char* ready, just go ahead with using that variable name directly, as shown below [I am also showing the usage of the unsigned long variable for a larger hex number. Do not confuse it with the case of having const char* instead of string]:
const char *hexString = "7FFEA5"; //Just to show the conversion of a bigger hex number
unsigned long hexNumber; //In case your hex number is going to be sufficiently big.
sscanf(hexString, "%x", &hexNumber);
This works just perfectly fine (provided you use appropriate data types per your need).
I had the same problem today, here's how I solved it so I could keep lexical_cast<>
typedef unsigned int uint32;
typedef signed int int32;
class uint32_from_hex // For use with boost::lexical_cast
{
uint32 value;
public:
operator uint32() const { return value; }
friend std::istream& operator>>( std::istream& in, uint32_from_hex& outValue )
{
in >> std::hex >> outValue.value;
}
};
class int32_from_hex // For use with boost::lexical_cast
{
uint32 value;
public:
operator int32() const { return static_cast<int32>( value ); }
friend std::istream& operator>>( std::istream& in, int32_from_hex& outValue )
{
in >> std::hex >> outvalue.value;
}
};
uint32 material0 = lexical_cast<uint32_from_hex>( "0x4ad" );
uint32 material1 = lexical_cast<uint32_from_hex>( "4ad" );
uint32 material2 = lexical_cast<uint32>( "1197" );
int32 materialX = lexical_cast<int32_from_hex>( "0xfffefffe" );
int32 materialY = lexical_cast<int32_from_hex>( "fffefffe" );
// etc...
(Found this page when I was looking for a less sucky way :-)
Cheers,
A.
just use stoi/stol/stoll
for example:
std::cout << std::stol("fffefffe", nullptr, 16) << std::endl;
output: 4294901758
This worked for me:
string string_test = "80123456";
unsigned long x;
signed long val;
std::stringstream ss;
ss << std::hex << string_test;
ss >> x;
// ss >> val; // if I try this val = 0
val = (signed long)x; // However, if I cast the unsigned result I get val = 0x80123456
Try this. This solution is a bit risky. There are no checks. The string must only have hex values and the string length must match the return type size. But no need for extra headers.
char hextob(char ch)
{
if (ch >= '0' && ch <= '9') return ch - '0';
if (ch >= 'A' && ch <= 'F') return ch - 'A' + 10;
if (ch >= 'a' && ch <= 'f') return ch - 'a' + 10;
return 0;
}
template<typename T>
T hextot(char* hex)
{
T value = 0;
for (size_t i = 0; i < sizeof(T)*2; ++i)
value |= hextob(hex[i]) << (8*sizeof(T)-4*(i+1));
return value;
};
Usage:
int main()
{
char str[4] = {'f','f','f','f'};
std::cout << hextot<int16_t>(str) << "\n";
}
Note: the length of the string must be divisible by 2
For those looking to convert number base for unsigned numbers, it is pretty trivial to do yourself in both C/C++ with minimal dependency (only operator not provided by the language itself is pow() function).
In mathematical terms, a positive ordinal number d in base b with n number of digits can be converted to base 10 using:
Example: Converting base 16 number 00f looks like:
= 0*16^2 + 0*16^1 + 16*16^0 = 15
C/C++ Example:
#include <math.h>
unsigned int to_base10(char *d_str, int len, int base)
{
if (len < 1) {
return 0;
}
char d = d_str[0];
// chars 0-9 = 48-57, chars a-f = 97-102
int val = (d > 57) ? d - ('a' - 10) : d - '0';
int result = val * pow(base, (len - 1));
d_str++; // increment pointer
return result + to_base10(d_str, len - 1, base);
}
int main(int argc, char const *argv[])
{
char n[] = "00f"; // base 16 number of len = 3
printf("%d\n", to_base10(n, 3, 16));
}

I need to find common prefix between two strings in C++

My strncpy function is not working, shows argument of type "cons char" is in compatible with parameter type "char"
And when I call out the prefix function in the main function it says i must have a pointer to function type
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
void prefix(const char s1[], const char s2[], char prefix[]);
int main()
{
char s1[30];
char s2[30];
char prefix[30];
cout << "Enter two sentences to store in two different strings" << endl;
cin.getline(s1, 30);
cin.getline(s2, 30);
prefix(s1, s2, prefix);
}
void prefix(const char a[], const char b[], char prefix[])
{
int size;
if (strlen(a) < strlen(b))
{
size = strlen(a);
}
else if (strlen(a) > strlen(b))
{
size = strlen(b);
}
else
{
size = strlen(a);
}
for (int i = 0; i < size; i++)
{
if (a[i] != b[i])
{
strncpy(a, b, size);
}
}
}
Not sure on your exact error, but it is probably like "error C2064: term does not evaluate to a function taking 3 arguments" or "error: ‘prefix’ cannot be used as a function".
The issue here is you declared a local variable with the name prefix, so it will take precedence over the global function prefix. Some types of variable may be callable (e.g. function pointers, std::function, etc.).
The best solution for that is generally to rename your local, but you can explicitly tell it to use the global scope if desired: ::prefix(s1, s2, prefix);.
There are further errors within the prefix function itself however, as strncpy(a, b, size); tries to copy to a "const" string, which is not allowed, presumably you meant to copy to the prefix string instead, and probably end the loop there.
However, for C++ it would also generally be better to use the std::string type. You can use std::getline(std::cin, my_std_string) to read lines, and prefix = my_std_string.substr(0, i) would be a way to copy part of a string.
For starters this declaration in main
char prefix[30];
hides the function with the same name declared in the global name space.
Either rename the function or the variable or use a qualified name for the function.
This loop
for (int i = 0; i < size; i++)
{
if (a[i] != b[i])
{
strncpy(a, b, size);
}
}
does not make sense and in this call
strncpy(a, b, size);
you are trying to change the constant array pointed to by the pointer a.
And there are many redundant calls of the function strlen.
The function can be declared and defined the following way as it is shown in the demonstrative program below.
#include <iostream>
char * common_prefix( const char s1[], const char s2[], char prefix[] )
{
char *p = prefix;
for ( ; *s1 != '\0' && *s1 == *s2; ++s1, ++s2 )
{
*p++ = *s1;
}
*p = '\0';
return prefix;
}
int main()
{
const size_t N = 30;
char s1[N];
char s2[N];
char prefix[N];
std::cout << "Enter two sentences to store in two different strings" << '\n';
std::cin.getline( s1, N );
std::cin.getline( s2, N );
std::cout << "The common prefix is \"" << common_prefix( s1, s2, prefix )
<< "\"\n";
return 0;
}
Its output might look like
Enter two sentences to store in two different strings
Hello C#
Hello C++
The common prefix is "Hello C"

C++ SDL 2.0 - Importing multiple textures using a loop

I don't know whether or not this is possible but I have used this technique in different languages but am struggling to use it in C++. I have 10 images that I am trying to load into an array using a loop as so:
for (int i = 0; i < 10; i++)
{
Sprite[i] = IMG_LoadTexture(renderer, "Graphics/Player" + i + ".png");
}
This however does not seem to work in C++ so I was wondering what I am doing wrong, or what can I do to get the same result without having to load each image individually like so:
Sprite[0] = IMG_LoadTexture(renderer, "Graphics/Player0.png");
My error is: "Expression must have integral or unscoped enum type"
Thanks for any help =)
You cannot do this:
"This is my number: " + (int)4 + "!";
This is illegal. It will give you an error for trying to operator+ a const char* and a const char[SOME_INT_GOES_HERE] or another error for trying to use operator+ to add an int onto a string. Things just don't work that way.
You'd either have to use C (i.e. snprintf()) or a string stream. Here's my test code for isolating your problem:
#include <iostream>
#include <string>
int main()
{
int a = 1;
std::string str = "blah";
std::string end = "!";
//std::string hello = str + a + end;// GIVES AN ERROR for operator+
std::string hello = "blah" + a + "!";
//const char* c_str = "blah" + a + "end";
//std::cout << c_str << std::endl;
std::cout << hello << std::endl;
return 0;
}
Here's an alternative solution using string streams.
#include <iostream>
#include <string>
#include <sstream>
int main()
{
int i = 0;
std::string str;
std::stringstream ss;
while (i < 10)
{
//Send text to string stream.
ss << "text" << i;
//Set string to the text inside string stream
str = ss.str();
//Print out the string
std::cout << str << std::endl;
//ss.clear() doesn't work. Calling a constructor
//for std::string() and setting ss.str(std::string())
//will set the string stream to an empty string.
ss.str(std::string());
//Remember to increment the variable inside of while{}
++i;
}
}
Alternatively, you can also use std::to_string() if you're using C++11 (which just requires -std=c++11) but std::to_string() is broken on some sets of compilers (i.e. regular MinGW). Either switch to another flavor where it works (i.e. MinGW-w64) or just write your own to_string() function using string streams behind the scenes.
snprintf() may be the fastest way of doing such a thing, but for safer C++ and better style, it is recommended you use a non-C way of doing things.
I had a similar problem and I solwed it this way:
#include <iostream>
using namespace std;
int main() {
string line;
for (int i = 0; i < 10; i++) {
line = "Graphics/Player" + inttostr(i) + ".png"; //I wrote inttostr function because built in inttostr functions messed up my program (see below)
char charger[line.length()]; //creating char array
for (int i = 0; i < sizeof(line); i++) {
charger[i] = line[i]; // copying string to char arry
}
Sprite[i] = IMG_LoadTexture(renderer, charger);
}
}
string inttostr(int integer) { //I know it isn't the best way to convert integer to string, but it works
string charakter;
int swap;
bool negativ = false;
if (integer < 0) {
integer = -integer;
negativ = true;
}
if (integer == 0) {
charakter = "0";
}
while (integer >= 1) {
swap = integer % 10;
integer = integer / 10;
charakter = char(swap + 48) + charakter;
}
if (negativ) {
charakter = "-" + charakter;
}
return charakter;
}

Extracting int for char array in C++

I am trying to extract single character from char array and converting it in to integer.
I need to extract number from code for example if user enters A23B,I need to extract 23 and store it in a single variable here is my code
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
int main()
{
char code[5] ={'\0'};
cout << "Enter Your Four Digit Code\nExample A23B\n";
cin.getline(code,5);
cout << "You typed:\n" << code;
int a = atoi(code[1]);
int b = atoi(code[2]);
cout << endl <<a <<"\t"<<b;
//Other processing related to number a and b goes here
}
but it's not working and produces the following errors
C:\helo\clan\Test\main.cpp||In function 'int main()':|
C:\helo\clan\Test\main.cpp|12|error: invalid conversion from 'char' to 'const char*'|
C:\helo\clan\Test\main.cpp|12|error: initializing argument 1 of 'int atoi(const char*)'|
C:\helo\clan\Test\main.cpp|13|error: invalid conversion from 'char' to 'const char*'|
C:\helo\clan\Test\main.cpp|13|error: initializing argument 1 of 'int atoi(const char*)'|
||=== Build finished: 4 errors, 0 warnings ===|
atoi takes a const char*, not char.
If you need to get '2' and '3' from "A23B":
int b = atoi(code + 2);
code[2] = 0;
int a = atoi(code + 1);
If you need to get '23' from "A23B" then:
int a = atoi(code + 1);
For common situation , why not using std::string and std::stringstream like this:
#include <string>
#include <sstream>
template <class T>
std::string num2string (const T &in)
{
static std::stringstream out;
out.str ("");
out.clear();
out << in;
return out.str();
}
template <class T>
T string2num (const std::string &in)
{
T out;
static std::stringstream tmp;
tmp.str ("");
tmp.clear();
tmp << in;
tmp >> out;
return out;
}
You can use these two functions converting string between nums(int,double...).
Why not
int a = int(code[1]-'0') * 10 + int(code[2] - '0');
i.e. Convert the two ASCII characters to the appropriate integers and then do the maths.
EDIT
You should check to ensure that the string is 4 characters long and characters 2 & are digits.
You pass a char to a function that expects char *, and you can't do that. Why not doing:
int a = code[1] & 0xff;
int b = code[2] & 0xff;
I think you want something like this:
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
int main()
{
char code[5] ={'\0'};
cout << "Enter Your Four Digit Code\nExample A23B\n";
cin.getline(code,5);
cout << "You typed:\n" << code;
char aStr[2] = {code[1], 0};
char bStr[2] = {code[2], 0};
int a = atoi(aStr);
int b = atoi(bStr);
cout << endl <<a <<"\t"<<b;
//Other processing related to number a and b goes here
}
And if you want 23 in one variable then maybe this:
char aStr[3] = {code[1], code[2], 0};
int a = atoi(aStr);
Your code is horribly unsafe (what if the user enters more than four digits? What if a line break takes up more than one byte?)
Try something like this:
int a, b;
std::string line;
std::cout << "Enter Your Four Digit Code (Example: A23B): ";
while (std::getline(std::cin, line))
{
if (line.length() != 4 || !isNumber(line[1]) || !isNumber(line[2]))
{
std::cout << "You typed it wrong. Try again: ";
continue;
}
a = line[1] - '0';
b = line[2] - '0';
break;
}
We need the isNumber helper:
inline bool isNumber(char c) { return '0' <= c && c <= '9'; }
If anyone wants to do this code with out including to many library's(Some schools require just basic libraries like mine)
This function is done with cmath and cctype
It will take in a course number like cs163 and turn it into an int of 163
ascii value for 1 = 49 that is why the - 48 is there.
Something like this will do it as well, but with out using a lot of function like string class.
This isn't super optimised I know, but it will work.
int courseIndexFunction(char * name){
int courseIndex = 0;
int courseNameLength = 5;
if (name[2] && name[3] && name[4]){
//This function will take cs163 and turn
//it into int 163
for (int i = 2; i < courseNameLength; ++i){
double x = name[i] - 48;
x = x * pow(10.0 , 4-i);
courseIndex += x;
}
}
return courseIndex;
}