scanf [^ \ n]循环执行,除了第一次以外,不停止等待用户输入 [英] scanf[^\n] in a loop , not stop to wait for user input except for 1st time

查看:130
本文介绍了scanf [^ \ n]循环执行,除了第一次以外,不停止等待用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用scanf(%[^''\ n"]输入一个句子.输入是循环的,我还有其他代码块来处理它.

如果我仅使用^ \ n以外的scanf(%s),则每个时间循环中,控制台将停止等待用户输入,这是我需要的正确例程.

但是,如果我使用scanf(%[^ \ n]或%[^''\ n''],仅在控制台第一次等待用户输入时,它将继续连续显示printf("Input:")而不会停止等待新输入.

我尝试将数组分配为null,可用数组空间,刷新流,但无济于事.

简单的示例代码和示例错误的输出:

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:

#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

推荐答案

您的scanf()语句错误,它不使用正则表达式.一种更简单的方法是使用 gets() [
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];


尽管如果您想输入长字符串,则20可能还不够.


Although 20 may not be enough if you want to enter a long string.


这篇关于scanf [^ \ n]循环执行,除了第一次以外,不停止等待用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆