Scanning an entry by scanf does not walk in the string beyond the white space

Asked

Viewed 195 times

1

I’m trying to make a program that reads a sentence and then capitalizes every initial of every word, if not already. The problem is that I type in a sentence but it only returns the first word, nothing else. the word is with the first letter capitalized but the other words of the sentence do not appear in the output.

#include<stdio.h>
#include<ctype.h>
char namechange( char abc[], int size);
int main()
{
    int i,n;
    char name[100000];
    scanf("%s", &name);

    namechange( name, n );

}


char namechange( char abc[], int size)
{
    int i, k = 0;
    for ( i = 0; abc[i] != '\0'; i ++)
    {
        int a,b;
        a = abc[i];
        b = abc[i - 1];
        if (i == 0 || 'b' == 8)
           abc[i] = toupper (abc[i]);
    }
    while ( abc[k] != '\0')
    {
        printf("%c", abc[k]);
        k = k + 1;
    }

    }

1 answer

3


This code makes no sense and does not compile. The main problem is that the scanf() interprets spaces inappropriately, so you need to ask him to format them properly. In fact anything other than simple exercises should not be used scanf().

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

void namechange(char abc[]) {
    for (int i = 0; abc[i] != '\0'; i++) {
        if (i == 0 || abc[i - 1] == ' ') abc[i] = toupper(abc[i]);
    }
    printf("%s", abc);
}

int main() {
    char name[1000];
    scanf("%[^\n]s", name);
    namechange(name);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thanks for the help, I did not understand the change ( formatting ) you made in scanf. I should use fgets preferably?

  • The fgets() is used in real applications, scanf() only for quick exercises or if it makes a lot of sense, which is rare.

  • The scanf is often used to make the times of strtol(), to read and parse numbers, but for strings it is very deficient.

  • 1

    @Wtrmute the scanf() not because he only reads stdin.

  • True. Properly it would be the fscanf() and the sscanf(); but the scanf() ends up being used in cases where the string would come from stdin, as in the example, but also in Unix-like applications that read stdin and write stdout.

  • scanf("%[ n]s", name)?

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.