-
Strings & Arrays
Hello,
I need a program that 's able to place a character anywere in a string. This is what Iv got so far.
#include <stdio.h>
main()
{
void strins(char string[], char character[], int position);
char string[30];
char str_ing;
int i = 0;
char character[1];
int position;
printf("Enter a string\n");
do
{
str_ing = getchar();
string[i] = str_ing;
i++;
} while(str_ing != '\n');
string[i-1] = '\0';
printf("the letter and postion of correction\n");
scanf("%s %d",character,&position);
strins(string,character,position);
}
void strins(char string[], char character[], int position)
{
int i;
for (i=0, j=0;string[i] == character[position]; ++i, j++ )
string[i] = character[position] + string[i];
puts(string);
}
IT's in the function im getting confused, Thanks for any help.
-
Try this, i changed a few things mainly i removed scanf and replaced it with fgets and sscanf, they're safer to use.
I also used pointers as they are less messy than a load of square brackets, enjoy.
Code:
#include <stdio.h>
void strins(char *str_ptr, char ch, int pos);
int main()
{
char string[31], temp[5], ch;
int pos;
printf("\nEnter a string ");
fgets(string, sizeof(string) - 1, stdin);
printf("\nEnter letter and position of correction ");
fgets(temp, sizeof(temp) - 1, stdin);
sscanf(temp, "%c %d", &ch, &pos);
strins(string, ch, pos);
return 0;
}
void strins(char *str_ptr, char ch, int pos)
{
str_ptr += (pos - 1);
*str_ptr = ch;
str_ptr -= (pos - 1); /* reset pointer */
puts(str_ptr);
return;
}