how to get an integer from a char array - c++

I have a char array that has '4''5'. But I want to convert those characters into actual integers so I subtract '0' from each index of the char array and store it into the same array. If I want to set an int called value to the 45 (the stuff inside the char array) How would I do it?

atoi() converts string to integer. For example if you already have the char array and integer variable declared you can do:
val = atoi(theCharArray);
Duplicate question

int int_value;
int_value = atoi(your_char_array);
the atoi() Function is used to convert string to int.
more information about atoi() Here.

Related

How to conver an char array to string on C++?

I need to convert a char array to string to use the string on a finite automaton, i've tried char[50]=string but it copies it indeed but has rubbish on in, char array has to be determinated, no more than 6 letters and i can't find another way, at least on C++ to make it, thanks a lot.
To assign a C style string (char array) to a std::string, you can use the following code:
std::string foo = c_style_string;
In addition, the variable on the left-hand side of the assignment operator (equal sign) is changed to the value of the variable on the right-hand side. char[50] = string will not compile.
Convert char array to string
char cArray[12] = "hello world";
string str(cArray);

Understanding char array[] and string

I am new to programming. I am learning C as my first programming language. I found something strange to understand.
I have learnt that in C we can represent a String as a sequence of characters like this (using a char array):
char status[10] = "Married";
I have learnt that the problem of this approach is that we have to tell the size of the status array during compilation.
But now I have learned we can use a char pointer to denote an string like -
char status[10] = "Married";
char *strPtr;
strPtr = status;
I don't understand it properly. My questions are -
How can I get char at index 4 (that is i in Married) using the strPtr?
In status there is a null character (\0) at the end of the string represented by the char array - M-a-r-r-i-e-d-\0. So by using the null character (\0) we can understand the end of the string. When we use strPtr, how can we understand the end of the string?
char *strPtr;
strPtr = status;
Now your pointer strPtr is pointing to the first character in the array and you can do
int i =0;
while( strPtr[i] != '\0')
{
printf("%c ",strPtr[i]);
i++;
}
*strPtr is called dereferencing the pointer to get the value stored in the location the pointer is pointing to.
Make a note that
strPtr[4] = *(strPtr +4);
Both will get you the value stored at the index 4 of the array.
Note the difference between a pointer and a array name:
----------------------------------
| s | t | r | i | n | g | \0 |
----------------------------------
|
strPtr
status
strPtr ++ will make your pointer point to the next element in the array.
| s | t | r | i | n | g | \0 |
----------------------------------
|
strPtr
Whereas you can't do this for the array name
status++ is not allowed because an array is not a modifiable lvalue.
Good to know:
char status[10] = "Married";
is just syntax sugar for the equivalent:
char status[10]; // allocate 10 Bytes on stack
status[0] = 'M';
status[1] = 'a';
...
status[6]= 'd';
status[7] = '\0'; // same as 0
Nothing more, nothing less.
Also:
char c = status[3];
is exactly the same as
char c = *(status+3);
The expression status[10] is mere syntactic sugar for *(status+10).
The \0 termination is used under the hood to check for the end, if you were implementing some string-handler yourself you could do this too, or you could ignore it and use some other parameter size given with the string, or you could (don't!) choose anything else as the termination symbol.
This isn't just true of char arrays, or 'strings', a C array is just a pointer to a contiguous block of like-typed stuff with a compile-time check that your 'array' subscripts don't go beyond the 'end' specified at time of declaration. With the *(array+offset) notation, you need to check this for yourself.
To get character at index 4 strPtr, you just use strPtr[4] (this also work for status).
To get the end of the string when using strPtr, you need to go through the characters and look for the terminating \0. This is what printf("%s", strPtr) does when it prints the string (and also when it parses the "%s" expression, which is just another string). To find a number of valid characters in the string in C, you use strlen() function. Oh, and make sure you dont do something like this:
char a[3];
strcpy(a, "Hello!");
As this will write 7 bytes into a three-byte memory space, and hence overwrite something you don't want overwritten.
I'm going to make a provocative statement: the way to think of this is that C doesn't have strings. C only has arrays of char. And despite its name, char is actually a numeric type ('A', for example, is just a funny way to write a number, usually 65).
An array of char is not really different from an array of int or any other array of numeric type; it's just that the language offers some extra ways to write objects of type char and arrays of them, and there is a general convention (systematized with functions like strlen) for how to interpret data stored in char arrays as being representations of strings.
char status[10]; // declares an array of `char` of length 10.
char *strPtr; // declare a pointer to `char`
strPtr = status; // make `strPtr` point to the first element of `status`
// Declare an array of 6 `char`, and initialize it.
char hello[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
// Shorthand notation for initializing an array of 6 `char` as above
char world[6] = "World";
// I want to store numeric data in this one!
char other[6] = {0, 1, 2, 3, 4, 5};
// "World" is shorthand for a constant array of 6 `char`. This is
// shorthand for telling the compiler to actually put that array in
// memory someplace, and initialize worldPtr to point to that memory.
const char *worldPtr = "World";
// This does the same thing as above. But it's still a *constant* array.
// You should *never* do this; it should be syntactically illegal to
// make a nonconstant `char*` to point to it. This is only allowed for
// historical reasons.
char *helloPtr = "Hello";
The '\0' at the end of the string is a useless add-on designed for easy or safety. You can tell string last character by using 'sizeof' like this:
char status[] = "Married";
size_t szLastCharstatus = sizeof(status) / sizeof(status[0]) - 2;
char chLastChar = status[szLastCharstatus];
Detailed explanation:
sizeof(status)
Returns the number of bytes array occpuies.
sizeof(status[0])
Returns the number of bytes first element occupies (and so the rest).
The division between those 2 values gives us the number of elements in the array. To access the last element now we need to subtract one 2 times because elements in array count from zero and because the last character in the string is '\0'.
Also note that arrays are not pointers and vice-versa. Arrays have an implicit conversion to pointer of their first element, constant size and their own type. They can be passed around by pointers or by value (using structure hack is required for the second).
Note that I'm using 'size_t' which is a type-def of a variable storing some size of data.

If a standard C++ library function returns an int for a char value, does it need to be casted?

For example, the ifstream function
ifstream infile;
infile.peek() //returns an integer
Do I need to cast this int return value as a char or can I compare it directly to another char?
If the latter is the case, does this mean char to char comparison just checks to see if integer ascii values are the same?
Thanks.
Comparing it with a char literal e.g 'c' should work due to Integral Promotion

C++ atoi with unsigned char

I got an unsigned char with the value of 1, I need to put this in a string like "1".
But if I try to put this directly into a stringstream it will get the value of char(1) and I need it to be "1".
I know that if I can get this into the function atoi it will return the "1" value.
But I tried to cast it to char and put it in the atoi function, but it throws an exception.
Already tried to put it in a string and them cast c_str() into atoi function, but without success yet.
If someone can help me I'll apreciate.
Simply cast a char to an int before inserting it into the std::stringstream:
ss << static_cast<int>(c);
This will treat the value of the char not as a character but as a numerical value.
I believe you're confusing two functions here.
You wish to convert an integer to a string.
atoi (ascii to integer) however takes a string and parses it into an integer, making "123" into 123.
You are looking for the itoa function here, which has this prototype:
char * itoa ( int value, char * str, int base );
In your case, this would look like this:
char Buf[10];
itoa(123, Buf, 10);
printf("%s", Buf); //Outputs 123
Please remember though, that itoa is not part of the standard, even though it is supported by some compilers. For a more standard-compliant version use:
sprintf(Buf, "%d", 123);
Of course all of this is plain C, but any C++ compiler will work with this all the same.
To convert a numeric value in the range [0,9] to the corresponding character, just add '0' to it. That's guaranteed to work on all systems.

initializer-string for array of array of chars is too long

I am making a patcher for a game but I get the error "initializer-string for array of array of chars is too long" from Mingw. I am trying to make a multidimensional array of chars to contain what functions to patch.
I have checked for other questions about this and found one where the asker forgot to add commas to the end of every string literal, but I have done that already.
Could anyone help me?
The source that triggers the error:
char patches2[][64] = {
"CreateMutexW",
"CreateRemoteThread",
"CreateRemoteThreadEx",
"?strcmp#unicode_string_trait#esl##SAJPB_W0#Z",
"??0?$CStringT#_WVunicode_string_trait#esl##Vunicode_string_implement#2##esl##QAE#XZ",
"??0?$CStringT#_WVunicode_string_trait#esl##Vunicode_string_implement#2##esl##QAE#PB_W#Z",
"??4?$CStringT#_WVunicode_string_trait#esl##Vunicode_string_implement#2##esl##QAEAAV01#PB_W#Z",
"?GetContent#?$CStringT#_WVunicode_string_trait#esl##Vunicode_string_implement#2##esl##QBEPB_WXZ",
"?SetLookUpOrder#CFileSystem#esl##QAEXW4EFileLookUpOrder#esl_constant#2##Z",
"??1package_file_item#esl##QAE#XZ",
"??1CFormatter#esl##QAE#XZ",
"??6CFormatter#esl##QAEAAV01#K#Z",
"??6CFormatter#esl##QAEAAV01#G#Z",
"??6CFormatter#esl##QAEAAV01#M#Z",
"??6CFormatter#esl##QAEAAV01#PB_W#Z",
"??BCFormatter#esl##QBE?AV?$CStringT#_WVunicode_string_trait#esl##Vunicode_string_implement#2##1#XZ",
"?__time#etc#esl##YAKXZ",
"?ReadFSAA#CGameOptionMgr#pleione##QAE?AW4EFSAA#pleione_constant#2#XZ",
"?ReadFSAAQuality#CGameOptionMgr#pleione##QAEKXZ",
"?CleanUp#CPleione#pleione##QAE_NXZ",
"?SetSkyTime#CAtmosphere#pleione##QAEXM#Z",
"?SetCamera#CCameraControl#pleione##QAEXPAVCScene#2#PAVITerrain#2#KFF#Z",
"?GetObjectId#CObject#mint##QBE_KXZ",
"?ReadU8#CMessage#mint##QAEEXZ",
"?GetLuck#IParameter#core##QAEMXZ",
"?GetGateLocalName#CGateMgr#core##QBE?BV?$CStringT#_WVunicode_string_trait#esl##Vunicode_string_implement#2##esl##AB v34##Z",
"?GetLife#IParameterBase2#core##QAEMXZ",
"?GetLifeMax#IParameterBase2#core##QAEMXZ",
"?IsEiry#SItemEgoInfo##QBE_NXZ",
"?SetFog#CDungeonRegion#core##QAEX_N#Z",
"?GetTargetCombatPower#ICharacter#core##QAE?AW4ECombatPower##PBname2##Z",
"?GetCombatPower#IParameterBase2#core##QBEMXZ",
"?GetInterfaceDurability#IItem#core##QBEKXZ",
"?GetInterfaceDurabilityMax#IItem#core##QBEKXZ",
"?GetColor#IItem#core##QBEKK#Z",
"?IsElf#ICharacter#core##QBE_NXZ",
"?IsGiant#ICharacter#core##QBE_NXZ",
"?IsPet#ICharacter#core##QBE_NXZ",
"?IsNPC#ICharacter#core##QBE_NXZ",
"?IsNamedNPC#ICharacter#core##QBE_NXZ",
"?IsGoodNPC#ICharacter#core##QBE_NXZ",
"?Compile#CDefaultCompiler#pleione##UAEPAVCCompiledText#2#ABV?$CStringT#_WVunicode_string_trait#esl##Vunicode_string_implement#2##esl##ABUtext_option#2##Z",
"?Compile#CDefaultTagCompiler#pleione##UAEPAVCCompiledText#2#ABV?$CStringT#_WVunicode_string_trait#esl##Vunicode_string_implement#2##esl##ABUtext_option#2##Z",
"?Compile#CHTMLCompiler#pleione##UAEPAVCCompiledText#2#ABV?$CStringT#_WVunicode_string_trait#esl##Vunicode_string_implement#2##esl##ABUtext_option#2##Z",
"?_RenderGlowOverlay#CRendererContext#pleione##AAEXXZ",
"?GetExploLevel#IParameterBase2#core##QBEGXZ",
"?GetExploExpPercent#IParameter#core##QBEMXZ",
"?ParseCommand#CUserConsoleMgr#core##QBE_NABV?$CStringT#_WVunicode_string_trait#esl##Vunicode_string_implement#2##esl##AAVCUserConsole#2##Z",
"?Instance#CLocalizer#core##SAAAname2#XZ",
"?GetLocalText#CLocalizer#core##QBE?AVCFormatter#esl##ABV?$CStringT#_WVunicode_string_trait#esl##Vunicode_string_implement#2##4##Z",
"?stdapi_ShowChattingMessage#core##YAX_KABV?$CStringT#_WVunicode_string_trait#esl##Vunicode_string_implement#2##esl##1KKE#Z",
"?stdapi_ShowCaption#core##YAX_KABV?$CStringT#_WVunicode_string_trait#esl##Vunicode_string_implement#2##esl##W4EMessageCaptionType##KKK0#Z",
"?stdapi_GetGlobalTime#core##YA_KXZ",
"?stdapi_GlobalTimeToGameTime#core##YAX_KAAK11#Z",
"?IsUsingNaosSupport#IServiceMgr#core##QBE_NXZ",
"?CheckFastStringID#IProp#core##QBE_NPB_W#Z",
"?IsUsableContents#IServiceMgr#core##QBE_NW4EServiceContents#2##Z",
"?IsTransformed#ITransformMgr#core##QBE_NXZ",
"?GetFullSuitID#ICharacter#core##QAEKXZ",
"?IsBroken#IItem#core##QBE_NXZ",
"?CheckFastStringID#IItem#core##QBE_NPB_W#Z",
"?IsExpired#IItem#core##QAE_N_K#Z",
"?IsArenaField#IRegion#core##QBE?B_NXZ",
"?CanAttackTarget#IPVPMgr#core##QBE_NPBVICharacter#2##Z"
};
char patches2[][64]
This is an array of arrays. The first dimension is determined automatically from the number of elements in the initializer. The second dimension is specified as being 64 chars.
Some of the string literals with which you initialize patches2 are longer than 64 characters in length. You need to increase the size to some value large enough to hold the largest C string in the initializer.
Well, the declaration for a single string looks like this:
const char* myString = "MyString";
What you probably want is an array of const char*s. You can change char patches2[][64] to const char* patches2[] (an array of pointers to const char).
The number of const char*s in patches2 can be calculated using sizeof():
const char* patches2[] = {"CreateMutexW", /* The rest... */ };
int numPatches = sizeof(patches2) / sizeof(const char*);
So if you add/remove some strings, you don't have to update the dimensions.