0

I'm a beginner with C++ and not too familiar with the language yet. So what would be the simplest way to fix my code? I think there's something wrong with userInput.insert(i, ""); but I'm not sure what.

Example: If the input is: -Hello, 1 world$! The output would be: Helloworld

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

int main() {
   string userInput;
   string lowerAlpha = "abcdefghijklmnopqrstuvwxyz";
   string upperAlpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
   
   getline(cin, userInput);
   
   for (int i = 0; i < userInput.size(); ++i) {
      for (int j = 0; j < 26; ++j) {
         if ((userInput.at(i) != lowerAlpha.at(j)) || (userInput.at(i) != upperAlpha.at(j))) {
            userInput.insert(i, "");
         }   
      }      
   }
   
   cout << userInput << endl;

   return 0;
}
TheGoldenTree
  • 158
  • 4
  • 16

1 Answers1

1

If your compiler supports the C++ 20 then you can use standard function std::erase_if with a lambda as for example

#include <string>
#include <cctype>

//...

std::erase_if( userInput, []( unsigned char c ) { return not isalpha( c ); } );

Otherwise use the standard algorithm std::remove_if with the member function erase as for example

#include <string>
#include <iterator>
#include <algorithm>
#include <cctype>

//...

userInput.erase( std::remove_if( std::begin( userInput ),
                                 std::end( userInput ),
                                 []( unsigned char c )
                                 {
                                     return not isalpha( c );
                                 } ), std::end( userInput ) );  

If to use your approach with for-loops then the code of the loops can look for example the following way

#include <iostream>
#include <string>
#include <string_view>
#include <cctype>

int main() 
{
    const std::string_view lowerAlpha = "abcdefghijklmnopqrstuvwxyz";
    const std::string_view upperAlpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    std::string userInput = "-Hello, 1 world$!";

    std::cout << userInput << '\n';

    for ( std::string::size_type i = 0; i < userInput.size(); )
    {
        if ( lowerAlpha.find( userInput[i] ) == std::string_view::npos &&
             upperAlpha.find( userInput[i] ) == std::string_view::npos )
        {
            userInput.erase( i, 1 );
        }
        else
        {
            ++i;
        }
    }

    std::cout << userInput << '\n';
}

The program output is

-Hello, 1 world$!
Helloworld
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • A more efficient algorithm than erasing each individual character. – Neil Sep 30 '22 at 23:52
  • `std::erase_if(user_input, std::not_fn(std::isalpha));` Except `#include ` might bring overloads of `isalpha` in which case you can do `std::erase_if(user_input, std::not_fn(std::isalpha));` and by this point I would use your lambda version. – bolov Oct 01 '22 at 18:05