Home > Mobile >  How to access c string by index for a integer number?
How to access c string by index for a integer number?

Time:01-19

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;
}

CodePudding user response:

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;
}

Explanation

'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 to int. And the final result that is used to initialize variable j on the left hand side will be the resultant of subtraction of those two promoted int values 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)

  1. ...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.

CodePudding user response:

  1. Construct a new string from character.
  2. Convert the substring to integer. Example:
#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;
}

CodePudding user response:

The solution is simple , just cast j to char . Example:

#include <iostream>
using namespace std;

main()
{
  string i = "123";
  int j = i[0];
  cout << char(j);
}

CodePudding user response:

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;
}

CodePudding user response:

Change j to be a char instead of an int:

#include <iostream>
#include <string>
using namespace std;

int main()
{
  string i = "123";
  char j = i[0];
  cout << j;
}
  •  Tags:  
  • Related