I am writing a simple program that compares a single character from argv[] to a character in a char array. This is done using a for loop to check if argv[1] is any of the characters in the character array, which is to serve as an input error check.
What I have done to implement this is below:
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
const char validCharacters[] = "abcde01234";
int goodChars = 0;
for (int i = 0; i < sizeof(validCharacters) - 1; i++) {
if (strcmp(argv[1], &validCharacters[i]) == 0) {
cout << "Characters match!" << endl;
goodChars++;
}
}
if (goodChars > 0) {
cout << "Input OK!";
}
else {
cout << "Invalid input!";
}
return 0;
}
I inputted '0' as the value for argv[].
When I was debugging, this, I found that strcmp(argv[1], &validCharacters[i])
returns -1, and that sizeof(argv[1])
returns 4.
Why is it that argv[1] has the size of 4 despite only having '0' entered into it? I'm certain that this is the reason why my program isn't working and would like to know if there is a way to resolve this problem.
Also, I'm not very experienced in C++, so anything you thing is bad practice, please let me know.
argv is an array of char pointers. In order to compare and get the size of the actual value, you'll have to dereference the char object. For example, to get the size:
if(*argv[1] == '0'){
// Do Something
}
Checks if the first argument(argv[0] is the command itself), is equal to the character '0'. Here I dereference the char at index 1 of the argv array.