In: Computer Science
Problem: Take 3 inputs string, integer, string. If incorrect number of lines are given then print an error message. Also have to make sure 2nd input is an integer and not a string by default. The function in the program should take the second string and insert it into the first string in the position indicated by the integer input given. The program cannot use strlen() or strncpy() functions and it should check the integer input to make sure it is in the bounds of the length of the first string or else it should give an error.
My current solution:
#include <stdio.h>
int main()
{
int num, l1, l2;
char* s1[], s2[];
char* test[];
printf("Please enter a string, integer, and a string: ");
scanf("%s %d %s", s1, &num, s2);
while (s1[i] != '\0')
{
l1++;
}
while (s2[i] != '\0
l2++;
}
result = (char*) malloc (sizeof(char) * (l1 + l2));
if(result == NULL)
{
printf("Error allocating memory");
exit(1);
}
for (int i = 0; i < num; i++)
{
result = s1[i];
}
for (int i = num; i < (l1+l2); i++)
{
result = s2[i];
}
printf("\n\nFinal string is: %s", result);
free(result);
return 0;
}
#include <stdio.h> #include <stdlib.h> // Returns int value if s is a number else -1 int isNumber(char *s) { int value = 0; int i = 0; while(s[i] != 0) { if (s[i] <= '9' && s[i] >= '0') { value = 10 * value + (s[i] - '0'); } else { return -1; } i++; } return value; } int main() { int i, num, l1=0, l2=0; char s1[100], s2[100], s3[100]; char test[100]; // read all input as string. printf("Please enter a string, integer, and a string: "); scanf("%s %s %s", s1, s2, s3); num = isNumber(s2); // check if s2 is number if(num == -1) { printf("invalid second number %s\n", s2); return 1; } i=0; while (s1[i] != '\0') { l1++; i++; } i=0; while (s3[i] != '\0') { l2++; i++; } if(num > l1) { printf("invalid position given.\n"); return 1; } char *result = (char*) malloc (sizeof(char) * (1 + l1 + l2)); if(result == NULL) { printf("Error allocating memory"); exit(1); } for (int i = 0; i < num; i++) { result[i] = s1[i]; } for (int i = 0; i < l2; i++) { result[num + i] = s3[i]; } for (int i = num; i < l1; i++) { result[l2 + i] = s1[i]; } result[l1 + l2] = '\0'; printf("\n\nFinal string is: %s", result); free(result); return 0; }