Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

printf() does not showing full sentence

I’m doing my school assignment and stuck in showing results.

#include <stdio.h>
#include <ctype.h>


int main(int argc, char *argv[]) {
    /* Declare input variable */
    char sentence[200];     // array that large enough for an sentence
    int i;

    /* Print the prompt */
    printf("Enter a sentence:");
    scanf("%s", &sentence);

    /* Change all white space characters to a space */
    for(i = 0; sentence[i]; i++)
    {
        if(isspace(sentence[i]))    //isspace to convert space, \t, \n
            sentence[i] = ' ';
    }

    /* Remove multiple spaces */
    i = 0;

    while(sentence[i] != '\0')      // \0 = NULL byte -> 0x30, address
    {
        if(sentence[i] == ' ' && sentence[i+1] == ' ')      // if there is two space
        for(int j = i; sentence[j]; j++)
        {
            sentence[j] = sentence[j+1];                    // eliminate one space
        }
        else
          i++;
    }


    sentence[0] = toupper(sentence[0]);     // Capitilize the first character of the sentence
    for(i = 1; sentence[i]; i++)
    {
        sentence[i] = tolower(sentence[i]);
    }

    /* Display the Output */
    printf("%s\n", sentence);

    return 0;
}

I followed the direction, but the result shows like this:
enter image description here

I tried to build and run the code after annotating middle part to see if the input is same as output. But it came out the same as in the picture. I don’t think it’s a problem with the middle part, but I don’t know what the problem is.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You don’t need an ampersand here:

scanf("%s", &sentence);

In fact, you cannot get the whole sentence with the help of a scanf function. You need functions like fgets here. For example:

fgets(sentence, sizeof sentence, stdin);

and your problem is solved.


A sample output:

Enter a sentence:this sentence has  a double  space 
This sentence has a double space
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading