Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ reading input from char* argv[]

Tags:

c++

arrays

I'm just learning C++ and am trying to write a program that will take in inputs from char* argv[] and process them.

Each argv[] will be 6 hexadecimal, e.g. 1A2B3C

I have a char array - char message[3]

and I'm trying to put 1A into message[0], 2B into message[1], and 3C into message[2].

I understand argv is kind of like a 2D array, so if my command line is:

./test 2 1A2B3C 4D5E6F

argv[2][0] would give me '1' and argv[2][1] would give me 'A'

but I don't know how to read 2 char together and put them into the char array.

Can anyone point me in the right direction?

like image 951
Jon Avatar asked Jun 05 '26 00:06

Jon


1 Answers

If the main function is declared like this

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

Calling

./test 1A2B3C 4D5E6F

will result in an argv array which looks similiar to

enter image description here

  • argc is the number of entries in argv
  • argv is an array of strings (actual a Pointer to the first element of an array of pointers to null-terminated multibyte strings)

In argv

  • the first entry is always the path and executable name, e.g. "/home/user/test" (the picture only shows test to keep things simple)
  • the remaining entries are the command line arguments ("1A2B3C" and "4D5E6F" in this case).
  • each entry in argv is in turn a character array

So for the example

  • argv[1] = ['1','A','2','B','3','C','\0']

To extract sub-strings from the arguments

  • Convert each argument to a string (std::string s(argv[1]) It's easier to work with strings than with char*
  • Extract sub strings (s.substr(0,2))
  • Convert each sub string to an integer (strtol(substring,NULL,16))

Try this example code

#include <iostream>
#include <stdlib.h> //required for string to int conversion

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

  std::cout << "executable= " << argv[0] << std::endl;

  for (int i=1; i<argc; i++) {
    std::string s(argv[i]); //put char array into a string

    std::cout << "arg["<<i<<"]="<<s<<std::endl;

    for (int j=0; j<6; j+=2) {

      std::string byteString = s.substr(j, 2);

      char byte = (char) strtol(byteString.c_str(), NULL, 16);

      std::cout << "byteString= "<<byteString << " as integer= "<<(int)byte<<std::endl;
    }
  }
}

Calling "./test 1A2B3C 4D5E6F" outputs

executable= /home/user/test
arg[1]=1A2B3C
byteString= 1A as integer= 26
byteString= 2B as integer= 43
byteString= 3C as integer= 60
arg[2]=4D5E6F
byteString= 4D as integer= 77
byteString= 5E as integer= 94
byteString= 6F as integer= 111

Alternatively, if the command line arguments could already be split, i.e.

"./test 1A 2B 3C 4D 5E 6F"

The substring extraction can be avoided.

like image 143
robor Avatar answered Jun 06 '26 16:06

robor