I want to convert an index in a string to an int in order to populate a 2D array of type int.
string s = "1 2 3";
a[0][0] = s.at(0);
I want a[0][0] to store the int value 1, but right now it's storing 49 with this method (which I am assuming is the direct conversion).
I have tried atoi, stoi, and static_cast, but I was getting a conversion error.
When you use
a[0][0] = s.at(0);
you are assigning the value of the character '1' to a[0][0], which is represented by the integral value of 49 in ASCII encoding.
If you are certain that there is only one digit, you can use
a[0][0] = s.at(0) - '0';
You can use a more flexible strategy.
std::istringstream str(s);
str >> a[0][0];
Gave wrong answer before:
This should work:
using namespace std;
int main ()
{
string str ("3");
int i = str.at(i) - 48;
cout << i <<endl;
return 0;
}
Related
This question already has answers here:
Multi-character constant warnings
(6 answers)
Closed 2 months ago.
void addItem(char selection) {
double total = 0.0;
qty = 0;
cout \<\< "Enter Qty: ";
cin \>\> qty;
`else if (selection == '10') {
total = 60 * qty;
cout << "Added to order"<<endl;
Iattotal += total;
Iatqty += qty;
Gtotal += Iattotal;
}
}
main.cpp:93:22: warning: multi-character character constant \[-Wmultichar\]
93 | if (selection == '10') {
| ^\~\~\~
^\~\~\~
It's there any solution for this peoblem I tried to change char to int but it didn't changed and i tried to find similar problems but it didn't fixed
Depends on what you want to do:
to read the value as an ascii code, you can write
char a = 'a';
int ia = (int)a;
/* note that the int cast is not necessary -- int ia = a would suffice */
to convert the character '0' -> 0, '1' -> 1, etc, you can write
char a = '4';
int ia = a - '0';
/* check here if ia is bounded by 0 and 9 */
The error is being produced because you are comparing a the "selection" variable, which is a char type, and can hold only one character, to '10' which is a multi-character constant.
If you are trying to pass a multi character variable, such as user input, to the function you might consider using a std:string.
Std::string can hold multiple characters, and can be compared using the == operator.
Alternatively, you could change the type to char * - this is how c-strings are normally defined. C-Strings are null terminated to denote the end of the string.
If you are using a c-string, you would need to use a library function like strcmp to compare the value to the constant.
strcmp returns 0 when the two strings are equal.
When dealing with c-strings you have to be careful not to read beyond the size of the buffer or array. For safety it is better to use strncmp, where the maximum number of characters to be compared can be specified.
For my university computer science course, our professor wants us to use a method of converting a string to an int (and int to string) without the use of any libraries such as sstream. I can't exactly find it anywhere in the notes/online and am hoping someone could show/tell me what it is and tell me how afterwards I would know that it has successfully been converted. All I know is that it involves using static_cast and also ASCII. He went over it quickly in class and I copied the code down quickly so there's a chance I could be missing something important or mistyped something, but here's what I got.
void intToStr(){
string numString = "2019";
int num = 0;
for(int i =0; i < numString.length(); i++){
char c = numString[i];
num = num * 10 + static_cast<int>(c) - static_cast<int>('0');
}
}
You don't have to create c as a char as that adds an extra step for conversion and can look overwhelming with static_cast
c++ will assign the ASCII value for a char if you assign it to an int so for example the char version of '2' has an ascii code of 50 to get it's integer value you subtract the char version of '0' as that is the first ascii value corresponding to digits, similarily if you want to get the number value of a letter say you're doing something like converting a string to a number you would first assign the letter to an int to get its ascii value and subtract the char 'a' or 'A' depending on what case you are working with and it would return that letters index in the alphabet, below is the code demonstrating what i'm taling about for numbers
// Example program
#include <iostream>
#include <string>
using namespace std;
int main(){
string numString = "2019";
int num = 0;
for(int i =0; i < numString.size(); i++){
int c = numString[i] -'0';
cout << c << endl;
num = num * 10 + c;
}
cout << num << endl;
}
For example:
string binaryValue = "11111111111111111111111111111011" // -5
I need to convert this string to decimal representatin of this number.
stoi(binaryValue, nullptr, 2)
Will throw exception on this case. So how can i do this in c++ ? String or int doesn't matter.
See the documentation of:
int std::stoi( const std::string& str, std::size_t* pos = 0, int base = 10 );
in particular:
The valid integer value [of str] consists of the following parts:
(optional) plus or minus sign
...
...
If the minus sign was part of the input sequence, the numeric value calculated
from the sequence of digits is negated as if by unary minus in the result type.
Exceptions
std::invalid_argument if no conversion could be performed
std::out_of_range if the converted value would fall out of the range of
the result type...
In the absence of a preceding minus-sign, the string:
std::string binaryValue = "11111111111111111111111111111011";
will be interpreted in a the call:
std::stoi(binaryValue, nullptr, 2);
as a non-negative integer value in base-2 representation. But as such,
it is out of range, so std::out_of_range is thrown:
To represent -5 as a string that your std::stoi call will convert as you expect,
use:
std::string const binaryValue = "-101";
Live demo
If you don't want to prefix a minus sign to a non-negative base-2 numeral, or cannot do so in your real-world
situation, but wish to interpret "11111111111111111111111111111011"
as the two's complement representation of a signed integer using the std::sto* API,
then you must first convert the string to an unsigned integer of a wide-enough
type, and then convert that unsigned value to a signed one. E.g.
#include <string>
#include <iostream>
int main()
{
auto ul = std::stoul("11111111111111111111111111111011",nullptr,2);
std::cout << ul << std::endl;
int i = ul;
std::cout << i << std::endl;
return 0;
}
Live demo
as you probably know number are stored as Twos Complement
to convert it using simple pseudocode
flip numbers 0->1, 1->0 from left to write util you find last 1 in string don't toggle this one
this will be your answer
0000000000000000000000000101=5
here is the code brouht from https://www.geeksforgeeks.org/efficient-method-2s-complement-binary-string/
#include<bits/stdc++.h>
using namespace std;
string findTwoscomplement(string str)
{
int n = str.length();
// Traverse the string to get first '1' from
// the last of string
int i;
for (i = n ; i >= 0 ; i--)
if (str[i] == '1')
break;
// If there exists no '1' concat 1 at the
// starting of string
if (i == 0)
return '1' + str;
// Continue traversal after the position of
// first '1'
for (int k = i-1 ; k >= 0; k--)
{
//Just flip the values
if (str[k] == '1')
str[k] = '0';
else
str[k] = '1';
}
// return the modified string
return str;;
}
int main()
{
string str = "11111111111111111111111111111011";
cout << findTwoscomplement(str);
//now you convert it to decimal if you want
cout<<"Hello World";
cout << stoul( findTwoscomplement(str),nullptr,2);
return 0;
}
preview at https://onlinegdb.com/SyFYLVtdf
I have to convert a decimal value into a string that shows the binary value, e.g. given 8, I need to print a string "1000". I have the conversion from decimal to binary, but when I print the values directly form the char array, I get little question marks instead of numbers. I know it has something to do with the way char arrays read values, but I can't figure out how to correct the issue.
void dec2Bin(int value, char binaryString[]) {
int remainder = 0;
int binDigit = 0;
int i = 0;
while (value != 0) {
binDigit = value % 2;
value /= 2;
binaryString[i] = char(binDigit);
i++;
}
for (int k = i - 1; k > 0; k--) {
cout << binaryString[k];
}
}
int main()
{
cout << "Enter a decimal number: ";
int num;
cin >> num;
char binaryString[20] = "";
dec2Bin(num, binaryString);
return 0;
}
When you do
binaryString[i] = char(binDigit);
you are assigning the decimal value 0 or 1 to binaryString[i]. That's okay, a char is basically nothing more than a small integer.
The problems comes when you want to print the value, as the only overloaded << operator to handle char treats the characters as a character, and in most encodings the values 0 and 1 are not printable.
There are two solutions:
Either you convert the character you want to print into a larger integer which won't be treated as a character:
cout << static_cast<int>(binaryString[k]);
Or you make the array contain actual printable characters instead:
binaryString[i] = binDigit + '0';
This question already has answers here:
Convert single char to int
(3 answers)
Closed 3 years ago.
I have a string which has 5 characters. I want to convert each single character to int and then multiply them with each other. This is the code :
int main()
{
int x;
string str = "12345";
int a[5];
for(int i = 0; i < 5; i++)
{
a[i] = atoi(str[i]);
}
x = a[0]*a[1]*a[2]*a[3]*a[4];
cout<<x<<endl;
}
It gives this error for the line with atoi :
invalid conversion from 'char' to 'const char*' [-fpermissive]|
How can I fix this? Thanks.
You can use:
a[i] = str[i] - '0';
Does a char to digit conversion by ASCII character positions.
The proper way to do this is std::accumulate instead of rolling your own:
std::accumulate(std::begin(str), std::end(str), 1, [](int total, char c) {
return total * (c - '0'); //could also decide what to do with non-digits
});
Here's a live sample for your viewing pleasure. It's worth noting that the standard guarantees that the digit characters will always be contiguous, so subtracting '0' from any of '0' to '9' will always give you the numerical value.
std::atoi takes a const char*(a null terminated sequence of characters)
Try to change like
a[i]= str[i]-'0';
You are supplying with a single char hence the compiler is complaining
str[i] is char not char *
Use following :-
int x;
std::string str = "12345";
int a[5];
for(int i = 0; i < 5; i++)
{
a[i] = str[i] -'0' ; // simply subtract 48 from char
}
x = a[0]*a[1]*a[2]*a[3]*a[4];
std::cout<<x<<std::endl;
look at this way
string str = "12345";
int value = atoistr.c_str());
// then do calculation an value in a loop
int temp=1;
while(value){
temp *= (value%10);
value/=10;
}