55.2k views
4 votes
Given string userString on one line and character updatedChar on a second line, change the last character of userString to updatedChar.

Ex: If the input is:

cheetah
S

then the output is:

cheetaS

Note: Assume the length of string userString is greater than or equal to 1. C++

1 Answer

2 votes

Answer:

#include <iostream>

#include <string>

using namespace std;

int main() {

string userString;

char updatedChar;

// Get the user's string

cout << "Enter a string: ";

cin >> userString;

// Get the updated character

cout << "Enter a character to replace the last character: ";

cin >> updatedChar;

// Replace the last character

int length = userString.length();

userString[length - 1] = updatedChar;

// Print the updated string

cout << "The updated string is: " << userString << endl;

return 0;

}

Step-by-step explanation:

This program gets the user's input string and the updated character, replaces the last character of the string with the updated character, and finally prints the updated string.

User Miga
by
7.3k points