繁体   English   中英

Visual Studio 2017中的c scanf_s不会工作超过一次

[英]c scanf_s in visual studio 2017 don't work more than once

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


const int lung = 41;


void main() {

 char ceva1[lung];
 scanf_s("%[a-zA-Z ]s", ceva1, sizeof(ceva1));
 printf("%s", ceva1);
 scanf_s("%[a-zA-Z ]s", ceva1, sizeof(ceva1));
 printf("%s", ceva1);

 _getch();
}

只有第一个printf_s有效,它只是将文本打印两倍。 我发现工作的唯一方法是在C ++中使用getline,但是我想最好在C中使用scanf。

scanf_s("%[a-zA-Z ]s",任何调用都不会占用Enter键入的'\\n''\\n'作为下一个要读取的字符@Serge Ballesta ,因此第二个调用不会读取任何内容如果代码检查了scanf_s()的返回值,则可能已经推论得出。

代替scanf**getc* ,使用fgets() @ user3121023读取一行,并根据需要舍弃可能的尾随'\\n'

if (fgets(ceva1, sizeof ceva1, stdin)) {
  ceva1[strcspn(ceva1,"\n")] = '\0';
  // use ceva1
}

避免在任何地方使用scanf*() ,即使读取数字也是如此。

char buf[80];
if (fgets(buf, sizeof buf, stdin)) {
  int a,b;
  if (sscanf(buf, "%d%d", &a, &b) == 2) {
    // use a, b
  }  
}

这个表达式:

"%[a-zA-Z ]s" 

应该:

"%[a-zA-Z ]"

注意没有尾随的“ s”`。

但是,这将停止输入任何非字母的字符(例如空格,标点符号或换行符或数字)。

如果要在一行上输入所有内容,请使用如下格式的字符串:

"%[^\n]"

如果您发布一些示例输入,我们可以在我们的帮助下更加具体。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM