I'm in a pinch right now as I should send this as an homework tomorrow.I couldn't figure out what the problem is for a very very long time and I'm new to these things.
#include "strutils.h"
#include <iostream>
#include <string>
#include <sstream>
usingnamespace std;
bool inputcheck(string s)
{
int i;
if(s.at(0) == '-')
{
i = 1;
}
elseif (s.at(0) == '+')
{
i = 1;
}
else
{
i = 0;
}
while(i < s.length())
{
if( (s[i]<'0') ||(s[i]>'9') )
{
returnfalse;
i++;
}
if((i == 1) && ((s.at(0)=='-') || (s.at(0)== '+')))
{
returnfalse;
}
else
{
returntrue;
}
}
}
int int_length(string s)
{
int i;
if(s.at(0) == '-')
{
i = 1;
}
elseif (s.at(0) == '+')
{
i = 1;
}
else
{
i = 0;
}
while(i < s.length())
{
if( (s[i]<'0') ||(s[i]>'9') )
return i;
i++;
}
if((i == 1) && ((s.at(0)=='-') || (s.at(0)>'+')))
{
return 0;
}
else
{
return i;
}
}
int main()
{
int x,y;
string input,input1;
cout<<"Please enter the initial coordinate of the agent: "<<endl;
cin >> input;
if((input.at(0) == '(') && (input.at(input.length()-1) == ')'))
{
int pos= input.find(',');
int pos_reverse= input.rfind(',');
if (( pos != string::npos) && (pos_reverse == pos))
{
string xstr,ystr;
xstr = input.substr(1, pos-1);
ystr = input.substr(pos+1, input.length()-pos-2);
if( inputcheck(xstr) && inputcheck(ystr))
{
stringstream(xstr)>>x;
stringstream(ystr)>>y;
}
}
}
cout<<"Please enter the action to execute: "<<endl;
cin >> input1;
while(input1.length() > 0)
{
if(input1.find("west") == 0)
{
input1 = input1.substr(4);
int a=int_length (input1);
if(a == 0)
{
input1=input1.substr(a); //This parts are the problem I think.
x+=atoi(a);
}
}
elseif(input1.find("south") == 0)
{
input1 = input1.substr(5);
int a=int_length (input1);
if(a == 0)
{
input1 = input1.substr(a); //and this part
y-=atoi(a);
}
}
elseif(input1.find("north") == 0)
{
input1 = input1.substr(5);
int a=int_length (input1);
if(a == 0)
{
y+=atoi(a); //and this part
input1=input1.substr(a);
}
}
elseif(input1.find("east") == 0)
{
input1 = input1.substr(4);
int a=int_length (input1);
if(a == 0)
{
int a=int_length (input1); //and this part
x+=atoi(a);
input1=input1.substr(a);
}
}
else
{
cout<<"Error"<<endl;
}
system("pause");
}
}
The program output should be something like this;
Please enter the initial coordinate of the agent: (3,5)
Please enter the action to execute: north3
The agent moves to: (3,8)
I couldn't figure out how to print out the "(3,8)" part and the program gives error with those atoi's above.What can I use instead of atoi and how can I print out the "(3,8)" part? Or are there any other problems besides these? Any help is highly appreciated.