-1
#include "stdafx.h"
#include "stdlib.h"

int _tmain(int argc, _TCHAR* argv[])
{
    char *dumb = (char*)malloc(50);
    scanf("%[^\n]s", dumb);
    printf("%s\n",dumb);

    scanf("%[^\n]s", dumb);
    printf("%s\n", dumb);

    return 0;
}

I need help with the code, if I run this code and write in the first scanf "Hellow World" it prints out 2 "Hello Worlds" and jumps over the other scanf , and well how do I fix it??

enter image description here

GingerPlusPlus
  • 5,336
  • 1
  • 29
  • 52
Ciomegu
  • 47
  • 5

2 Answers2

0

First of all dont use C style cast, use static cast instead:

auto dumb = static_cast<char*>(malloc(50));

and you need cin.ignore() after first printf to clear up the buffer:

auto dumb = static_cast<char*>(malloc(50));
scanf("%[^\n]s", dumb);
printf("%s\n", dumb);
std::cin.ignore();
scanf("%[^\n]s", dumb);
printf("%s\n", dumb);

or you can use solution mentioned in the comment section:

scanf("%49[^\n]%*c", dumb);
vishal
  • 2,258
  • 1
  • 18
  • 27
0

Empty your input buffer after scanf.

char *dumb = (char*)malloc(50);
scanf("%[^\n]s", dumb);
fflush(stdin);  //flush remaining input buffer
printf("%s\n",dumb); 


scanf("%[^\n]s", dumb); 
fflush(stdin);
printf("%s\n", dumb);
JaeJun LEE
  • 1,234
  • 3
  • 11
  • 27