Problem with argv input

I'm trying to verify the input from a little test program.
All I want to do is to be sure the user enter the '-' character before his arguments

1
2
3
4
5
6
7
8
9

bool verifyInput(int argc, char* argv[]){
		std::cout << argv[1] << std::endl;
		if(argv[1] == "-"){
			std::cout << "test_ok";
                        return(true);
		}
		
	}


Even if I call the program with only '-', it doesn't verify the "if" condition.
I'd like to know if I'm doing it wrong or if I've forgot something...

Thanks
Last edited on
You can't use == for C strings - it will compare the memory locations -
You can use it with C++ strings:
1
2
3
4
5
6
7
8
#include <string>
bool verifyInput(int argc, char* argv[]){
		std::cout << argv[1] << std::endl;
		if( std::string(argv[1]) == "-"){
			std::cout << "test_ok";
                        return(true);
		}
	}

Or you can use C functions:
1
2
3
4
5
6
7
8
#include <cstring>
bool verifyInput(int argc, char* argv[]){
		std::cout << argv[1] << std::endl;
		if( !strcmp( argv[1], "-") ){
			std::cout << "test_ok";
                        return(true);
		}
	}


thanks a lot... I didn't realize it was only a type problem.
Another option would be to compare only the first element of argv[1] with the character '-'. In addition don't forget to check if argv[1] contains an argument. If it is a pointer pointing to NULL you'll get an access-violation error message.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include "../getch.h"
#include <string>

int main(int argc, char *argv[])
{
	if(argv[1] != NULL)
	{
		std::cout << argv[1] << std::endl;
	
		if(argv[1][0] == '-')
			std::cout << "yay";
	}
	
	getch();
}


As soon as you want to compare strings i suggest to use one of the options written by Bazzy.
You can check that argv[1] exists using argc
Topic archived. No new replies allowed.