Scanf("%[^\n]s", s); Not working in C languages

#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <ctype.h>

int main()
{
	char option, result;
	int input, read , a, b, c;
	int i;
	char s[100];

	do{
            printf("ENTER 1 FOR WHOLE SENTENCE CAPITALIZATION:\n");
            printf("enter 2 for whole sentence lowercase:\n");
            printf("Enter 3 For Every 1st word Capitalization:\n");

            scanf("%d", &input);

            printf("Enter your text here: ");
            scanf("%[^\n]s", s);

            switch(input) {
                case 1 : for (i = 0; s[i]!='\0'; i++) {
                    if(s[i] >= 'a' && s[i] <= 'z') {
                            s[i] = s[i] - 32;
                    }
                }
                printf("\nSENTENCE CAPITALIZED = %s\n", s);
                break;

                case 2 : for (i = 0; s[i]!='\0'; i++) {
                    if(s[i] >= 'A' && s[i] <= 'Z') {
                            s[i] = s[i] + 32;
                    }
                }
                printf("\nsentence lowercased = %s\n", s);
                break;

                case 3 : for(i=0; s[i]!='\0'; i++) {
                            if(i==0) {
                                    if((s[i]>='a' && s[i]<='z'))
                                    s[i]=s[i]-32;
                                    continue;
                                    }
                            if(s[i]==' ') {
                                ++i;
                                if(s[i]>='a' && s[i]<='z') {
                                    s[i]=s[i]-32;
                                continue;
                        }
                    }
                else {
                    if(s[i]>='A' && s[i]<='Z')
                    s[i]=s[i]+32;
                    }
                }

            printf("1st Letter Capitalized = %s\n",s);
            break;
                        }


printf("Do you want to continue?(y/n)\n");
    option=getche();

    }while(option=='y');

    return 0;
}

Use getchar(); before reading the string and before reading the value of option

2 Likes

Thank you so much…it worked like a charm…but can you please tell me why that was needed…I am still confused.

2 Likes

In some of the basic compilers, if we take the input of the string/character after any input then ENTER/RETURN KEY is assigned to the next input (string/character input), thus, compiler does not wait for the string/character input and assigns the ENTER/RETURN key value (0x10) to the string/character.
That’s why we are using getchar() to store that character so that we can take proper input.

1 Like