Click here to Skip to main content
15,908,112 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
I need to use scanf("%[^'\n']" to input a sentence. And the input is in a loop, I have other code block to process it.

If I just use scanf(%s) other than ^\n,each time loop the console will stop to wait user input, that's correct routine I need.

However, if I use scanf(%[^\n] or %[^'\n'], only the 1st time the console wait for user input, then it will continue display printf("Input:") continuously without stop to wait the new input.

I tried assign array to null, free array space, flush stream, not helpful.

Simple sample code and sample incorrect output:
C#
#include <stdio.h>

void userInput(){

  char* in;
  in=malloc(sizeof(char)*20);
  printf("Input: ");
  scanf("%[^'\n']",in);
  fflush(stdin);
  free(in);
}

void main(void) {

  for(;;)
    userInput();
}</stdio.h>


Sample Malfunction output:
Input:I enter something
Input: Input: Input:........Input
Posted
Updated 13-May-11 23:30pm
v3
Comments
Fabio V Silva 14-May-11 5:28am    
Edited formatting.

1 solution

Your scanf() statement is wrong, it does not use regular expressions. An easier way would be to use gets()[^]. There is also little point in using malloc() and free() in your subroutine. Just allocate the required number of characters on the stack thus:
char in[20];

Although 20 may not be enough if you want to enter a long string.
 
Share this answer
 
Comments
Member 7751939 14-May-11 5:49am    
Actually I use char in[20] before, same problem persist with scanf[^\n] in loop. So I try to use malloc free.
gets() solve the problem.thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900