How do i edit this program for j to contain "1"?
Currently it shows 49 which is the ascii value i think.
#include <iostream>
using namespace std;
main()
{
string i = "123";
int j = i[0];
cout << j;
}
You can do this as shown below:
int main()
{
std::string i = "123";
int j = i[0] - '0'; //this is the important statement
std::cout << j;
}
'0' is a character literal.
So when i wrote:
int j = i[0] - '0';
The fundamental reason why/how i[0] - '0' works is through promotion.
In particular,
both
i[0]and'0'will be promoted toint. And the final result that is used to initialize variablejon the left hand side will be the resultant of subtraction of those two promotedintvalues on the right hand side.
And the result is guaranteed by the Standard C++ to be the integer 1 since from C++ Standard (2.3 Character sets)
- ...In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.
So there is no need to use magic number like 48 etc.
#include <iostream>
using namespace std;
main() {
string i = "123";
// Method 1, use constructor
string s1(1, i[0]);
cout << s1 << endl;
// Method 2, use convertor
int j = atoi(s1.c_str());
cout << j << endl;
}
You have to subtract ASCII '0' (48) from the character digit:
#include <iostream>
using namespace std;
int main()
{
string i = "123";
int j = i[0] - 48; // ASCII for '0' is 48
// or
// int j = i[0] - '0';
cout << j;
}
'0' is the correct character digit for any encoding, not only ASCII. Using the magic number 48 would be forcing ASCII while '0' is portable to any C++ implementation.
<string>, which is the contracted mandate for bringingstd::stringto your C++ party. If it "works" without it, it is by chance; not design, and engineers don't like coding by chance.'0'fromjstd::stringmust be fully defined even if you have only included<iostream>. However, I agree you should still include<string>so you don’t accidentally calls non-member functions that are only defined in<string>