Hi this is my first post on this site. I am a beginner in c in college. I am writing the program in XCode.
My assignment is to ask the user for a string, ask for a substring to replace, ask what to replace it with, and then print out the original string with the replaced substring. I am allowed to use any functions in <string.h> aside from strstr.
i have had errors with my code for a while now and now am receiving the error
Program received signal: “EXC_BAD_ACCESS”.
at the "else" part of the "stringAtStart" function"
for some reason it is not looping properly i think. and when i try debugging it manually "with printf's" that specific "else" keeps running continuously.
i really need your help.
thank you in advance!
Code:
#include <stdio.h>
#include <string.h>
#define Max 40
int stringAtStart(char string1[], char string2[], int Si);
/******
function name: main
the input: none
the output: none
the function operation: asking the user to pick a number between 1 and 3 and then based on the number picked computing 3 different options
******/
int main (void)
{
int pickednum, i;
char string1[Max], string2 [Max], string3 [Max];
do{
do
{
printf("Please enter option\n");
scanf("%d", &pickednum);
if (pickednum>3)
printf("illegal option \n");
} while (pickednum > 3);
switch (pickednum)
{
case 1:
printf("Please enter a string\n");
scanf("%s", string1);
printf("Please enter string to replace\n");
scanf("%s", string2);
printf("Please enter replacing string\n");
scanf("%s", string3);
//for (i=0; string1 [i] != '\0'; i++)
//printf("%d", contains (string1, string2, i));
for(i=0; i<strlen(string1); i++)
{
if(stringAtStart(string1,string2, i))
{
puts(string3);
i=i+strlen(string2);
printf("4 \n");
}
else
puts (string1[i]);
}
}
} while (pickednum !=3);
if (pickednum = 3)
exit;
}
int stringAtStart(char string1[], char string2[], int Si)
{
int i = Si, index=0, counter = strlen(string1), inString = 0;
for (i ; index < strlen(string2); i++)
{
if (counter == 0)
{
inString =1;
printf("1 %d\n", counter);
break;
}
if ((string1[i] == string2[index]) )
{
counter --;
index ++;
printf("2 counter = %d lengthofstring2 = %d string2= %d index = %d\n", counter,strlen(string2), strlen(string1),index);
}
else
{
counter = strlen(string1);
index=0;
printf("3 counter = %d index = %d\n", counter, index);
}
}
return inString;
}