0

I'm totally new student for c++ and finished watching some c++ tutorials for 5 - 6 hours long.

I didn't know what to study, so decided to work watch one of the tutorials of c++ and kinda following what the youtuber is doing.

While I'm working on it, I didn't get few lines of code which are

int main( int argc, char *argv[])

grid[x][y] = to_string(number).c_str()[0];

First of all, I didn't know we can put some parameters inside of main function parentheses and I don't get

to_string(number).c_str()[0]

Can someone explain these?

#include <iostream>
#define GRID_SIZE 3

using namespace std;


int main( int argc, char *argv[]){

   char grid[GRID_SIZE][GRID_SIZE];

    int number = 1;
    for (int x = 0; x < GRID_SIZE; x++){

        for(int y = 0; y < GRID_SIZE; y++){
            grid[x][y] = to_string(number).c_str()[0];
            number += 1;
            }
         }
    printf("\n------------\n");
    for (int x = 0; x < GRID_SIZE; x++){

            for (int y = 0; y < GRID_SIZE; y++){
                printf(" %c |", grid[x][y]);
            }
            printf("\n------------\n");
        }
    return 0;
}
Imanpal Singh
  • 1,105
  • 1
  • 12
  • 22
  • `int main( int argc, char *argv[])` is very basic `c++`: [https://stackoverflow.com/questions/4207134/what-is-the-proper-declaration-of-main](https://stackoverflow.com/questions/4207134/what-is-the-proper-declaration-of-main) – drescherjm May 02 '20 at 02:09
  • 2
    The only explanation that you need is that whoever wrote this doesn't really know C++ very well. This is just a completely convoluted way to get the first digit of a number, by converting it to a string and then reading the first character of the resulting string. This is a completely bass-ackwards way of doing this: converting the number to a string, and then plucking off its first character. Please promise me you will never write something like this in C++, yourself. – Sam Varshavchik May 02 '20 at 02:09
  • My advice is to start with one of the 2 beginner/ Introductory, no previous programming experience books here: [https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) read them cover to cover following the exercises in each chapter. This should take several months to complete. – drescherjm May 02 '20 at 02:16

1 Answers1

1

It gets char from the leftmost digit of number. It can be done shorter

to_string(number)[0]

Suppose number is 12, then to_string(number) is "12"s, finally to_string(number)[0] is '1'.

It can be done even more shorter assuming number is between 0 and 9.

number + '0'
273K
  • 29,503
  • 10
  • 41
  • 64