Question about argv error checking with string

I want to check if the input in argv is contains only the arguments in this array
char validCharacters[] = ".,‐+eE0123456789";
For instance argv[1] is only valid if it contains the characters in the previous array. If it doesn't , the input is invalid and one must display "X".

This is what i have so far. Getting error with strcmp function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  int i = 0;


		char validCharacters[] = ".,‐+eE0123456789";
	for (i; argv[1][i] != '\0'; i++)
	{
		
		
		
		for (int j = 0; validCharacters[j] != '\0'; j++)
		{
			if (strcmp(argv[1][i]), (validCharacters[j]))
			{
				cout << 'X' << endl;
				return 0;
			}
		}
	}




	}
wrong function. strcmp compares 2 strings, for example is "bob" == to "bob". You don't have that scenario, you have an 'is this in that' scenario.
here is a really simple way to do this.

bool is_legal[256] = {false};
is_legal['.'] = true;
...//assign all the rest, you can do the numbers in a loop to save tedium
for(i = '0'; i<='9'; i++)
is_legal[i] = true;
and so on.
now just parse your string:
bool check = true;
for(i = 0; i < strlen(argv[1]; i++)
check = check&&is_legal[argv[1][i]];

if(check)... etc

I think there is a function that can check for whether a string has only legal floating point symbols in it built into the language.... you are probably re-creating the wheel here.

you can also shovel argv[1] into a c++ string variable
string argv1 = argv[1];
and use modern code instead of C if you want to. I think its overkill, but if you don't know C strings very well its a better solution than trying to learn the C functions.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>
using namespace std;

bool isvalid( const char *test )
{
   const char *validCharacters = ".,-+eE0123456789";
   return string( test ).find_first_not_of( validCharacters ) == string::npos;
}

int main( int argc, char *argv[] )
{
   if ( argc > 1 && isvalid( argv[1] ) ) cout << argv[1];
   else                                  cout << 'X';
}
Last edited on
and if what you are doing is what i think you are doing, you can do something like this (shamefully stolen from web. I don't do much interface to humans, so validation is safely ignored here).

1
2
3
4
5
6
7
8
9
10
bool is_numeric (std::string const & str) 
{
    auto result = double();
    auto i = std::istringstream(str);

    i >> result;      
    i >> std::ws;  

    return !i.fail() && i.eof();
}
Yes, I'm having suspicions about an XY problem, @jonnin.
Topic archived. No new replies allowed.