mardi 21 février 2023

How do I replace specific characters in a string read from input with another character if they are digits? [closed]

I am trying to replace the first and third characters in a string read from input with the character '=' (using <cctype> library). This is what I have so far:

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main() {
   string userCode;

   getline(cin, userCode);
   
   char firstChar = userCode.at(0);
   char thirdChar = userCode.at(2);
   if (isdigit(firstChar) && isdigit(thirdChar)) {
      firstChar = '=';
      thirdChar = '=';
      userCode.at(0) = firstChar;
      userCode.at(2) = thirdChar;
   }
   else {
      userCode;
   }
      
   cout << userCode << endl;

   return 0;
}

But I keep getting inconsistent results? In some test cases, like

Input
465
Output
=6=

It seems to work, but then in others like

Input
11c
Output
11c
Expected output
=1c

It just doesn't for some reason? It also seems as if the test cases where it doesn't work, the digit that goes unreplaced is 1 or 3. Could this have to do with the fact that I am only trying to replace the first and third characters of the string? What is the issue here??? As you can see I've already tried to remedy the issue by making the first and third characters their own char variables in advance, rather than calling them directly using .at within the if statement, as I thought maybe the issue had to do with memory allocation or something at first, but I got the same result.

Apologies in advance if I broke any conventions or rules in asking this question, I am new to this website. Just a noob to C++ trying to give it my all. Thanks guys.

Aucun commentaire:

Enregistrer un commentaire