In: Computer Science
Q) You have been asked to develop a program which processes C++ null-terminated strings to extract character and numerical data separately. Assume that the users runs the application (examTest.exe) from the command line as follows: examTest.exe X-Axis:10,Y-Axis:17,Z-Axis:-6 Your application should step through the input arguments and extract the values of the XAxis, Y-Axis and Z-Axis commands. The user must always enter the arguments in the specified order, however your application should check they are correct. At the end of your application, the values of X-Axis, Y-Axis and Z-Axis should be stored as separate integers.
Note: Done accordingly. Please comment for any problem. Please Uprate. Thanks
Code:
#include<iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
bool startsWith(const char *a, const char *b)
{
if(strncmp(a, b, strlen(b)) == 0) return 1;
return 0;
}
int main(int argc, char* argv[]) {
if(argc<2){
cout<<"Usage: examTest.exe
X-Axis:#,Y-Axis:#,Z-Axis:# \n";
return 1;
}
try{
int x,y,z;
vector<string> vect;
string s(argv[1]);
stringstream ss(s);
while( ss.good() )
{
string
substr;
getline( ss,
substr, ',' );
vect.push_back(
substr );
}
for(int
i=0;i<vect.size();i++)
{
int n =
vect.at(i).length();
// declaring
character array
char
char_array[7];
strcpy(char_array, vect.at(i).c_str());
char *next =
strtok(char_array, ":");
string
s(next);
if(s.compare("X-Axis") == 0){
next = strtok(NULL, ",");
if(next!=NULL){
x=atoi(next);
}else{
throw exception("Invalid
Input");
}
}else
if(s.compare("Y-Axis") == 0){
next = strtok(NULL, ":");
if(next!=NULL){
y=atoi(next);
}else{
throw exception("Invalid
Input");
}
}else
if(s.compare("Z-Axis") == 0){
next = strtok(NULL, ":");
if(next!=NULL){
z=atoi(next);
}else{
throw exception("Invalid
Input");
}
}else{
throw exception("Invalid Input");
}
}
cout<<"Value of X-Axis is
:"<<x<<endl;
cout<<"Value of Y-Axis is
:"<<y<<endl;
cout<<"Value of Z-Axis is
:"<<z<<endl;
}catch(exception){
cout<<"Usage: examTest.exe
X-Axis:#,Y-Axis:#,Z-Axis:# \n";
return 1;
}
system("pause");
return 0;
}
Output: