1
#include<stdio.h>
int main(){
    char arr[20];
    int a;
    int count=0;
    while(1){
        printf("enter string with space:");
        fflush(stdin);
        scanf("%[^\n]%*c", arr);
        printf("enter integer:");
        scanf("%d",&a);
        count++;
        if(count==4){
            break;
        }
    }
}

I want to read string with space and I have to use this code. I wrote this in while loop and I want to read string and after integer number and it does not work.

Output:

enter string with space:hey hey

enter integer:159

enter string with space:enter integer:

But output should be:

enter string with space:hey hey

enter integer:159

enter string with space:.... heyy

enter integer: 1235
Clifford
  • 88,407
  • 13
  • 85
  • 165
jack1919
  • 13
  • 3

2 Answers2

2

fflush() is not defined input streams such as stdin. You will find that it works on Microsoft's C library, but not GNU.

Your scanf() call is incorrect. The first format specifier is incorrect, and you have no format specifier for string ;

scanf("%*[^\n]%*c") ;

will discard any remaining buffered characters to the end of the line inclusive. It accepts no input - it is not clear what string is or what you want to do with it. I'd suggest using a separate input call for that, for clarity.

Another somewhat less arcane solution is:

int c ;
while ((c = getchar()) != '\n' && c != EOF) { }
Clifford
  • 88,407
  • 13
  • 85
  • 165
  • I was just told to use fflush code while read string with space and I typed incorrectly something while editing the question, now I've edited it. – jack1919 May 22 '21 at 06:59
  • @jack1919 : But it is still incorrect in exactly the same way, changing `string` to `arr` does not change that. You have omitted the `*` in `%*[^\n]`. Never transcribe your code manually, copy & paste it for accuracy. Otherwise you are asking about code we cannot see while posting misleading code. – Clifford May 22 '21 at 07:04
  • Note this is an answer to the original question before it was edited, and also to the question implied in the title. It does not address the whole question as it now stands. – Clifford May 22 '21 at 07:11
0
enter string with space:enter integer:

This happens because after you enter integer input, \n is still left in the stream. %[ does not skip leading whitespace unlike most other format specifiers. Change scanf("%[^\n]%*c", arr); to scanf(" %[^\n]%*c", arr); so it manually skips the leading whitespace before taking input.

As for fflush(stdin), that is undefined behavior (see Using fflush(stdin)). @Clifford already provides two nice solutions to that issue.

mediocrevegetable1
  • 4,086
  • 1
  • 11
  • 33
  • 1
    indeed; my answer is to the original question, not the edited question - which is a different question that it originally appeared. – Clifford May 22 '21 at 07:10