Home > Software engineering >  Replacing a char in a char array not working from a variable
Replacing a char in a char array not working from a variable

Time:12-09

I am trying to write a program that takes in 5 characters then takes in a number and a letter and switches the character at the index/number to the new character. I think I have it but it is not working and defaulting the number to 0.

Also, is there a way to get both inputs at the same time?

  char str[5];
  int index;
  char temp;
  printf("Enter five characters\n");
  scanf("%s", str);
  printf("Please enter a number.\n");
  scanf("%d", &index);
  printf("Please enter a letter.\n");
  scanf("%s", &temp);
  str[index - 1] = temp;
  printf("The five characters are now %s\n", str);

accessing the char array with the index variable is giving me the first element always.

CodePudding user response:

FYI: I haven't code in C for a long, long time; however, I did run this code below successfully. You might have to review it and fix other things I might have missed.

First, we will change the first scanf by indicating we want only 5 characters scanf("\", str); and I'm indicating we want the last position in the array to have.

Next, we will do a for loop because we want to only accept an index between 1 to 5.

Finally, and this is important, we change the scanf to get one character; however, this isn't intuitive as before, because you need a space before the character indicator: scanf(" %c", &temp);

Code:

#include <stdio.h>

int main()
{
    char str[5];
    
    printf("Enter five characters\n");
    scanf("\", str);
    
    int index = -1;
    while (index < 1 || index > sizeof(str)){
        printf("Please enter a number 1 to %d.\n", (int) sizeof(str));
        scanf("%d", &index);
    }
    
    char temp;
    printf("Please enter a letter.\n");
    scanf(" %c", &temp);
    
    str[index - 1] = temp;
    printf("The five characters are now %s\n", str);

    return 0;
}

Result:

Enter five characters
12345
Please enter a number 1 to 5.
1
Please enter a letter.
x
The five characters are now x2345


...Program finished with exit code 0
Press ENTER to exit console.

CodePudding user response:

#include <stdio.h>


int main()
{
    char str[5];
    int index;
    char temp;

    printf("Enter five characters\n");
    scanf("%s", str);
    printf("Please enter a number.\n");
    scanf("%d", &index);
    printf("Please enter a letter.\n");
    scanf(" %c", &temp);
    str[index - 1] = temp;
    printf("The five characters are now %s\n", str);
    return 0;
}

Output:

Enter five characters
12345
Please enter a number.
2
Please enter a letter.
x
The five characters are now 1x345
Press any key to continue . . .
  • Related