-1

I got headache because of this code (I already known 'about the dangers of "gets" function, but still want to use it).

I'm using Code::Blocks, F9->type '1', enter->the progress runs pass gets function, and does not let me type the input.

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

int ngat()//stop function
{
    int thoat;
    printf("\nNhap '1' de tiep tuc hoac '0' de thoat: ");//1:continue,0:exit
    scanf("%d",&thoat);
    switch(thoat)
    {
        case 1:main();
        case 0:break;
    }
}

void upper(char s1[])
{
    int i=0;
    while(s1[i]!='\0')
    {
        if (s1[i] >= 'a' && s1[i] <= 'z')
        {
         s1[i] = s1[i] - 32;
        }
        i++;
    }
}

int main()
{
    system("cls");
    puts("1.Viet ham upper (doi ki tu sang ki tu hoa)\n2.Viet ham lower (doi ki tu sang ki tu thuong)\n3.Viet ham proper (doi ki tu dau sang ki tu hoa");
    int sobai;
    printf("\nNhap so cua bai: ");
    scanf("%d",&sobai);
    switch(sobai)
    {
        case 1:
        {
            system("cls");
            char s1[255];
            printf("\nViet ham upper (doi ki tu sang ki tu hoa)");//string upper function
            printf("\nNhap xau:");//input string
            gets(s1);
            upper(s1);
            printf("%s\n",s1);
            ngat();
            break;
        }
    }
}
Zoran Jankov
  • 236
  • 2
  • 5
  • 18

1 Answers1

0

The problem with above code is scanf() reads an integer and leaves a newline character in buffer. So gets() only reads newline and the string that you expect is ignored by the program.

How to solve this problem?

  • make scanf() to read a new line by using an extra “\n”, i.e., scanf(“%d\n”, &sobai) . In fact scanf(“%d “, &sobai) also works (Note extra space).
  • add a getchar() after scanf() to read an extra newline.
Abhishek Keshri
  • 3,074
  • 14
  • 31