How to output a single character when using char * [] = "something"

I played with pointers to better understand them, and I came across what I think I should have done, but can't figure out how to do this. The code below works fine - I can output "a", "dog", "socks" and "pants", but what if I just want to get the "o" out of the "socks"? How should I do it?

char *mars[4] = { "a", "dog", "sock", "pants" };

for ( int counter = 0; counter < 4; counter++ )
{
  cout << mars[ counter ];
}

Please forgive me if the question is answered somewhere - there are 30+ pages related to the C ++ pointer, and I spent about 90 minutes looking at them, and also read various (very informative) articles before making a decision .

+3
source share
5

mars[i][j] j 'th i.

, mars[2][1] - 'o'.

+7

, . , std::string -class (, , ++), STL-Sequence. , -. :

mars[i][j]

, mars

std::vector< std::string > mars;

++. , , , , . , ++ iterators, .

+2
cout << mars[2][1] ;

marsis an array char *, so to get an individual char you need to index into a char array

+1
source

mars[counter]has a type char *indicating a character string with a null character. So you could:

for ( int counter = 0; counter < 4; counter++ ) 
{ 
  char * str = mars[ counter ]; 
  size_t len = strlen(str);

  if (len >= 2)
    cout << str[1]; 
} 
0
source

Since others have suggested an easy way, please also find one round way to do this;)

char *myChar = &mars[ 1 ][0];
int nPosOfCharToLocate = 1;
myChar = myChar + nPosOfCharToLocate;
cout <<*myChar<<endl;
0
source

Source: https://habr.com/ru/post/1743291/


All Articles