Determining the string length of a command prompt input

I am currently writing a program for my C++ class that takes two numbers from the command prompt and performs arithmetic on them as specified by the last parameter. The valid inputs of the last parameter are a,s,m,d and p. I've figured out how to read the last parameter as follows:

1
2
3
4
5
int main(int argc, char *argv[])
...
char c;
c=*argv[3];
...


My problem is that if the last input were, for example, "af" or "a298" this would be considered valid since it only detects the first character, "a", and not any other characters that may follow it. The only solution I can think of is to determine if the string length of the last parameter is greater than 1 using "strlen" but I can't figure out how to use it with command prompt inputs. Is there a way to do this or does anyone have any other suggestions as to how I can solve this issue?
Are you looking for something like this?

1
2
3
4
5
6
7
char* x;
if(argc == 2){
 if(strlen(argv[1]) != 1){
  printf("ERROR");

 }
}
Last edited on
strlen(argv[x]);
Alternatively, check that argv[x][1]==0.
There's also !strcmp(argv[x],"a").
I always just convert them to a std::vector of std::string and forget all the C lib stuff.
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>  // to output the result
#include <sstream>   // to convert a string to a number
#include <string>    // string handling
#include <vector>    // fancy-pants array
using namespace std;

int main( int argc, char** argv )
  {
  vector <string> args( argv, argv+argc );

  ...

Now you can use all the vector and string methods to do stuff. You can check that there are exactly 4 arguments (prog name, num1, num2, op), and like jmc and helios suggest, check that args[ 3 ].length() is exactly one. Etc.

Hope this helps.
Topic archived. No new replies allowed.