Deletion of any Non-ascii characters present in C++

If you were facing complexity in removing the presence of any Non-ASCII character from a String in C++. Then my friend you’ve come to the right place. In this tutorial, I’m going to show and explain, how this complex chunk of algorithm works, but first let us learn, What is ASCII and what does the term Non-ASCII mean ?.

So now every character which you may not find on your keyboard form the Non-ASCII characters which include signs, emojis, etc.

Deletion of the non-ASCII characters in C++

#include <stdio.h>
#define maxlength 100
void inputLine(char *line)
 {
     char c;
     while((c=getchar())!='\n')*(line++)=c;
     *line='\0';
 }
void printLine(char *line)
 {
     while(*line!='\0')printf("%c",*line++);
     printf("\n");
 }

 void removeNonAscii(char line[],char modifiedline[])
 {
     int i=-1;
     int j=-1;
     while(line[++i]!='\0'){
        if(!(line[i]>=0&&line[i]<=127))continue;
        else modifiedline[++j]=line[i];
     }
     modifiedline[++j]='\0';
 }
 int main()
  {
      char line[maxlength];
      char modifiedline[maxlength];
      printf("Input a line: ");
      inputLine(line);
      printf("The line given input, after removing non-ascii characters, is: ");
      removeNonAscii(line,modifiedline);
      printLine(modifiedline);
      return 0;
  }

 

Summary :

We first import the standard i/o library and define the ‘maxlength’ to be 100 throughout the program. A program always receives its flow of control from the main. So in the main we define a character array of name ‘line’ and ‘modifiedline’ and set them to length 100. We then take input with the function ‘inputLine’, which we had created.
After that we pass the string received from the user to the function ‘removeNonAscii’ which takes the parameters of inputted string and an empty string. We then use a while loop to flow through the string, thus checking each character and if the character does not lie in the ASCII range of ‘0’ to ‘127’ we go to the next character, but if it does; we store it in the empty character array, After the loop completes and all the desired characters have been stored in the empty array, We finally print it to get the output.

Output:

Input a line:The cross will disappear †

 

 

After removing non-ascii characters,is: The cross will disappear

 

Self-Created functions used:

  • void inputLine()             – to take an input in the form of character array.
  • void printLine()              – to print the character array.
  • void removeNonAscii() – to remove any non-ASCII character and store it in a different array.





Leave a Reply

Your email address will not be published. Required fields are marked *