In: Computer Science
An issue that we have been constantly facing is determining whether valid characters exist in the command line arguments for the laboratory tests. Many solutions rely on stepping through the argument list determining whether the current character is valid via a series of 'if' statements. Whilst this approach is certainly effective it is often prone to error. Consider an array of suitable characters for an application as follows:
const char validCharacters[] = ".,-+eE0123456789";
Utilising nested 'for' loops, the characters in argv[1] could be examined to see whether it was one in the list provided by the array validCharacters. A Boolean flag (true or false) can be utilised to determine whether an invalid character exists and an error message output. Set the command-line arguments to ’34.0’. Based on the discussed concepts, create a small C++ application that uses nested loops to confirm that the characters in argv[1] are valid. If an invalid digit is found, display an ‘X’ on the console window and immediately exit. Change the input argument to ‘3,512t’ and determine confirm that your application functions correctly. Hint: Consider using the function strlen() to determine the length of the input argument.
validchar.cpp
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
const char validCharacters[] = ".,-+eE0123456789";
// checking if word provided for validating
if (argc < 2)
{
cout << "no word provides" << endl;
exit(-1);
}
string input_word = argv[1];
// looping through word
for (int i = 0; i < input_word.length(); i++)
{
bool found = false;
// looping through valida char
for (int j = 0; j < 17; j++)
{
if (input_word[i] == validCharacters[j])
{
// if word found making boolean variable as true and
// breaking the loop
found = true;
break;
}
}
// if char not in valid char then printing the error message
if (!found)
{
cout << "Error: invalid character " << input_word[i] << endl;
return -1;
}
}
// if no error then printing X only
cout << "X" << endl;
return 0;
}
// OUT
Please do let me know if u have any concern...