std::string part into integer - c++

I have a std::string: 01001, I want to get each number:
std::string foo = "01001";
for (int i=0; i < foo.size(); ++i)
{
int res = atoi( foo[i] ); // fail
int res = atoi( &foo[i] ); // ok, but res = 0 in any case
}
How to do that?

This is the easiest way I see:
std::string foo = "01001";
for (int i=0; i < foo.size(); ++i)
{
int res = foo[i] - '0';
}

If you know all characters of foo are digits, you can use (int) (foo[i] - '0') which subtracts the ascii value of '0' from the character. This works for all digits because their ascii values are consecutive.
Your first attempt fails because foo[i] is a single char, while atoi() takes a cstring. Your second attempt fails because &foo[i] is a reference to that character.

Each digit can be obtained by simply using subtraction:
int res = foo[i] - '0';
atoi takes a null-terminated string, not an individual character. The subtraction approach works because the ten decimal digits are guaranteed to be consecutive in the character set (obviously, if there is a chance that you'll have nondigit characters in the string, you'll want to do proper error handling).

One simple way, very close to what you have, would be to insert the char into a predefined string, as such:
std::string foo = "01001";
char str[] = {" "};
for (int i=0; i < foo.size(); ++i)
{
str[0] = foo[i];
int res = atoi( str );
}

Related

If a string is an array of char, how do you convert it into an array of interger

I kept getting an error with this loop. If there are something i missed, please help. Thank You!
int main(){
string hasil;
int cod[5];
hasil = "99999";
for(int i = 0; i < 5; i++){
cod[i] = stoi(hasil[i]);
}
for(int i = 0; i < 5; i++){
cout << cod[i] + 1;
}
std::stoi() takes a std::string, not a char. But std::string does not have a constructor that takes only a single char, which is why your code fails to compile.
Try one of these alternatives instead:
cod[i] = stoi(string(1, hasil[i]));
cod[i] = stoi(string(&hasil[i], 1));
string s;
s = hasil[i];
cod[i] = stoi(s);
char arr[2] = {hasil[i], '\0'};
cod[i] = stoi(arr);
stoi is for converting entire strings to integers, but you're only giving it single characters.
You could either build strings from each character like so:
cod[i] = std::stoi(std::string(1, hasil[i])); // the 1 means "repeat char one time"
Or calculate the actual integer yourself using a bit of ascii math (assuming everything is a valid digit):
cod[i] = hasil[i] - '0'; // now '0' - '0' returns 0, '5' - '0' returns 5, etc...
The below complete working program shows how you can achieve what you want:
#include <iostream>
int main(){
std::string hasil;
int cod[5];
hasil = "99999";
for(int i = 0; i < 5; ++i)
{
cod[i] = hasil[i] - '0';
}
for(int i = 0; i < 5; i++){
std::cout << cod[i];
}
return 0;
}
The output of the above program can be seen here.
std::stoi only accpet std::string or std::wstring as an argument type. But hasil[i] is a char
In C++, '0' to '9' is guarantee to be ascending in ACSII values, so, you can do this:
cod[i] = hasil[i] - '0';

how can I convert character to integer number

How could I change an array of character (string) to an integer number without using any ready function (ex atoi();) for example :-
char a[5]='4534';
I want the number 4534 , How can I get it ?
Without using any existing libraries, you have to:
Convert character to numeric digit.
Combine digits to form a number.
Converting character to digit:
digit = character - '0';
Forming a number:
number = 0;
Loop:
number = number * 10 + digit;
Your function will have to check for '+' and '-' and other non-digits characters.
First of all this statement
char a[5]='4534';
will not compile. I think you mean
char a[5]="4534";
^^ ^^
To convert this string to a number is enough simple.
For example
int number = 0;
for ( const char *p = a; *p >= '0' && *p <= '9'; ++p )
{
number = 10 * number + *p - '0';
}
Or you could skip leading white spaces.
For example
int number = 0;
const char *p = s;
while ( std::isspace( ( unsigned char )*p ) ) ++p;
for ( ; *p >= '0' && *p <= '9'; ++p )
{
number = 10 * number + *p - '0';
}
If the string may contain sign '+' or '-' then you can check at first whether the first character is a sign.
You can go like this
It's working
#include <stdio.h>
#include <string.h>
#include <math.h>
int main()
{
char a[5] = "4534";
int converted = 0;
int arraysize = strlen(a);
int i = 0;
for (i = 0; i < arraysize ; i++)
{
converted = converted *10 + a[i] - '0';
}
printf("converted= %d", converted);
return 0;
}
I prefer to use the std::atoi() function to convert string into a number data type. In your example you have an non-zero terminated array "\0", so the function will not work with this code.
Consider to use zero terminated "strings", like:
char *a = "4534";
int mynumber = std::atoi( a ); // mynumber = 4534

Trying to reverse a string in C++, but gibberish appears at the of the reversed string?

Here is my function to reverse a string:
void reverse(char *str){
int lengthStr = strlen(str);
int j, i;
char reversedString[100];
for (j = 0, i = lengthStr-1; i >= 0; i--, j++){
reversedString[j] = str[i];
}
cout << reversedString;
}
The string does appear as reversed, but at the end there's a bunch of weird characters that appears. What could be causing this issue?
If you want to reverse the string there are many cleaner approaches already available like: std::reverse_copy etc.
But if you want to fix this function then try this:
char reversedString[100];
memset(reversedString, 0, 100*sizeof(char);
OR
for (j = 0, i = lengthStr-1; i >= 0; i--, j++){
reversedString[j] = str[i];
}
reversedString[j] = '\0'; //! Add null character at the end to indicate end of the string
cout << reversedString;
Note: Your program fails if input string has length >= 100.
Add a zero to the characters you assigned to reversedString. Otherwise, the unitialized extra portion of the new string will show up as garbage. A zero is used to mark the end of the string.
First of all the function is invalid and has no sense. You do not reverse the original string and the local string that is defined in the function can be less than the original string. Also you do not append the reversed local string with the terminating zero. The function can look like
void reverse( char *str )
{
size_t n = std::strlen( str );
for ( size_t i = 0; i < n / 2; i++ )
{
char c = str[i];
str[i] = str[n - i - 1];
str[n - i - 1] = c;
}
}
The original reversed string can be displayed in the code that calls the function.

How to replace certain items in a char array with an integer in C++?

Below is an example code that is not working the way I want.
#include <iostream>
using namespace std;
int main()
{
char testArray[] = "1 test";
int numReplace = 2;
testArray[0] = (int)numReplace;
cout<< testArray<<endl; //output is "? test" I wanted it 2, not a '?' there
//I was trying different things and hoping (int) helped
testArray[0] = '2';
cout<<testArray<<endl;//"2 test" which is what I want, but it was hardcoded in
//Is there a way to do it based on a variable?
return 0;
}
In a string with characters and integers, how do you go about replacing numbers? And when implementing this, is it different between doing it in C and C++?
If numReplace will be in range [0,9] you can do :-
testArray[0] = numReplace + '0';
If numReplace is outside [0,9] you need to
a) convert numReplace into string equivalent
b) code a function to replace a part of string by another evaluated in (a)
Ref: Best way to replace a part of string by another in c and other relevant post on SO
Also, since this is C++ code, you might consider using std::string, here replacement, number to string conversion, etc are much simpler.
You should look over the ASCII table over here: http://www.asciitable.com/
It's very comfortable - always look on the Decimal column for the ASCII value you're using.
In the line: TestArray[0] = (int)numreplace; You've actually put in the first spot the character with the decimal ASCII value of 2. numReplace + '0' could do the trick :)
About the C/C++ question, it is the same in both and about the characters and integers...
You should look for your number start and ending.
You should make a loop that'll look like this:
int temp = 0, numberLen, i, j, isOk = 1, isOk2 = 1, from, to, num;
char str[] = "asd 12983 asd";//will be added 1 to.
char *nstr;
for(i = 0 ; i < strlen(str) && isOk ; i++)
{
if(str[i] >= '0' && str[i] <= '9')
{
from = i;
for(j = i ; j < strlen(str) && isOk2)
{
if(str[j] < '0' || str[j] > '9')//not a number;
{
to=j-1;
isOk2 = 0;
}
}
isOk = 0; //for the loop to stop.
}
}
numberLen = to-from+1;
nstr = malloc(sizeof(char)*numberLen);//creating a string with the length of the number.
for(i = from ; i <= to ; i++)
{
nstr[i-from] = str[i];
}
/*nstr now contains the number*/
num = atoi(numstr);
num++; //adding - we wanted to have the number+1 in string.
itoa(num, nstr, 10);//putting num into nstr
for(i = from ; i <= to ; i++)
{
str[i] = nstr[i-from];
}
/*Now the string will contain "asd 12984 asd"*/
By the way, the most efficient way would probably be just looking for the last digit and add 1 to it's value (ASCII again) as the numbers in ASCII are following each other - '0'=48, '1'=49 and so on. But I just showed you how to treat them as numbers and work with them as integers and so. Hope it helped :)

how to shuffle char "abcdefghijklmnopqrstuvwxyz" without repeating

const char chars[] = "abcdef ....";
char result[...];
memcpy(result, chars, sizeof(chars));
for (unsigned i = 0; i < (sizeof(chars)-1); ++i) {
unsigned j = rand() % sizeof(chars);
char tmp = result[j];
result[j] = result[i];
result[i] = tmp;
}
problem writing the result to a text file.
The answer to "how to shuffle" something in C++ is to use one of the standard library's shuffling algorithms. An easy way to do it would be to put it in an std::string, and use std::random_shuffle:
std::string s = "abcdef ...." ;
std::random_shuffle(s.begin(), s.end());
You can also do it with an array:
char letters[] = {'a', 'b', ..... };
std::random_shuffle(letters, letters+26);
Here you go: Fisher–Yates shuffle.
And a C++ implementation.
Your problem is that the character value 0 isn't mapped to A. Rather, a character which will will be printed as A is equal to 65. You can see the full table here, if you ever need it.
Anyway, the code solution is simple.
Instead of
cout<<letter[i]<<" ";
You can do:
cout<<letter[i]+'A'-1<<" ";
(the -1 is because you numbered the letters from 1 to 26 instead o 0 to 25).
const char chars[] = "abcdef ....";
char result[...];
memcpy(result, chars, sizeof(chars));
for (unsigned i = 0; i < (sizeof(chars)-1); ++i) {
unsigned j = rand() % sizeof(chars);
char tmp = result[j];
result[j] = result[i];
result[i] = tmp;
}
If you use STL then std::random_shuffle is preferred.