简体   繁体   中英

C++ reading input from char* argv[]

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, eg 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?

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

在此输入图像描述

In argv

  • the first entry is always the path and executable name, eg "/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, ie

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

The substring extraction can be avoided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM