Home > front end >  print space instead of integer
print space instead of integer

Time:10-07

here is the code

#include <cs50.h>
#include <stdio.h>
#include <string.h>

int main (void) {

    string text = get_string ("plaintext:");

    for (int i=0; text[i] !='\0'; i  ) {

        int s = (int) text[i];

        printf ("%i ",s);

    }

    printf("\n");

}

and here is the expected output of this

./scrabbleee
plaintext:this is a string
116 104 105 115 32 105 115 32 97 32 115 116 114 105 110 103 

How to stop space 32 ascii value to print? Can I print space instead of 32?

CodePudding user response:

In C there is the standard function isblank that determines whether the given character is the space character ' ' or the tab character '\t'.

So you can write

#include <cs50.h>
#include <stdio.h>
#include <string.h>

int main (void) {

    string text = get_string( "plaintext: " );

    for ( size_t i = 0; text[i] !='\0'; i   ) {

        if ( isblank( ( unsigned char )text[i] ) )
        {
            printf( "%c ", ' ' );
        }
        else
        {  
            printf ( "%i ", text[i] );
        }

    }

    printf("\n");
}

So if a tab or space character will be encountered in a string then the space character ' ' will be outputted.

Pay attention to that there is no need to cast a character to the type int like

int s = (int) text[i];

before the call

printf ( "%i ", text[i] );

because due to the integer promotions the character will be promoted to the type int implicitly.

Also it is desirable to change this statement

printf ( "%i ", text[i] );

to

printf ( "%i ", ( unsigned char)text[i] );

if you want to output all values of characters as unsigned values. In this case the program will not depend on the used character set ASCII or EBCDIC.

And never use magic numbers like 32 as it is advised in other answers.:)

CodePudding user response:

You can display it as a character if it's 32:

if (s != 32) {
    printf ("%i ",s);
} else {
    printf ("%c ",s);
}

I did not work with C for a looong time, but if you can use the ternary operator for strings, then you can do this as well:

printf((s != 32) ? "%i " : "%c ");

CodePudding user response:

Here is the answer to the question including @Lajos's answer. There are only two cases, so print 'space' or none 'space'

#include <cs50.h>                         
#include <stdio.h>                        
#include <string.h>                       
                                          
int main (void) {                                             
  string text = get_string ("plaintext:");
  for (int i=0; text[i] !='\0'; i  ){     
    int s = (int) text[i];                
    printf ((s != 32)? "%i ": " ", s);    
  }                                       
  printf("\n");                           
}                                         
  • Related