Reputation: 147
The goal of the program is to be able to extract integers in a string(char), only if they are inside a set of parenthesis. I am also suppose to print out an error message if the string doesn't meet these requirements.
For example: char str = "( 1 2 3)";
this would print that it found integers 1, 2, and 3. But lets say str was char str = " 1 2 3( 4 5 6);
would return a call to my error function because it has bad formatting. If the string contains anything else that is not a number or white space it should print error also. Lastly it is suppose to check looking inside the parenthesis until it finds the end parenthesis.
At the moment, I can search thru any string and extract the integers but I cannot figure out how to determine if there are anything else besides numbers and check only inside parenthesis.
void scanlist(char *str)
{
char *p = str;
while (*p) {
if ((*p == '-' && isdigit(p[1])) || (isdigit(*p))) {
int val = strtol(p, &p, 10);
on_int(val);
}
else {
p++;
}
}
I have tried putting another if statement after the while seeing if it starts with a '(' but it doesn't do anything. Please and thanks!
Upvotes: 0
Views: 105
Reputation: 49
Hope this helps
int main()
{
//variable declerations
int j = 0;
// str is the string that is to be scanned for numbers
string str= "(123)";
//iterator to point at individual characters in a string
//It starts at the beginning of a string
//a string is an array of characters
string::iterator p = str.begin();
//if the iterator that i named p does not find the bracket at the begining
//prints out an error massage
if(*p != '(')
{
cout<<"error";
}
//else if it finds a bracket at the begining goes into the loop
// I use *p to veiw the content that the iterator points to
// if you only use p you will get the address which is a bunch of wierd numbers like A0Bd5
if(*p == '(')
{
//while loop to move the iterator p one caracter at a time until reach end of string
while(p != str.end())
{
// if end bracket is reached end loop
if(*p == ')')
{
break;
}
//if it finds a digit prints out the digit as character not as int!
if(isdigit(*p))
{
cout<<*p<<endl;
}
//increments the iterator by one until loop reach end of string it breaks
p++;
}
}
//to pause the screen and view results
cin.get();
}
Upvotes: 0
Reputation: 182619
You need to hold some state regarding your position. For example:
int inside_paren = 0;
while (*p) {
switch (*p) {
case '(':
if (inside_paren)
/* error */
inside_paren = 1;
break;
case ')':
/* ... */
inside_paren = 0;
break;
default:
if (!isdigit(*p) || !inside_paren)
/* error */
}
}
Upvotes: 3