简体   繁体   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();
}

Only the first printf_s work, it just printf twice the text. 只有第一个printf_s有效,它只是将文本打印两倍。 The single way that i found to work is in c++ with getline but i want to do it in c with scanf preferably. 我发现工作的唯一方法是在C ++中使用getline,但是我想最好在C中使用scanf。

Neither call to scanf_s("%[a-zA-Z ]s", consumes the '\\n' keyed in with Enter . '\\n' remains as the next character to be read @Serge Ballesta . So the 2nd call reads nothing. Had code checked the return value of scanf_s() , this may have been deduced. scanf_s("%[a-zA-Z ]s",任何调用都不会占用Enter键入的'\\n''\\n'作为下一个要读取的字符@Serge Ballesta ,因此第二个调用不会读取任何内容如果代码检查了scanf_s()的返回值,则可能已经推论得出。

Instead of scanf* and *getc* , read a line with fgets() @user3121023 , and lop off the potential trailing '\\n' if desired. 代替scanf**getc* ,使用fgets() @ user3121023读取一行,并根据需要舍弃可能的尾随'\\n'

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

Avoid using scanf*() anywhere, even for reading numbers. 避免在任何地方使用scanf*() ,即使读取数字也是如此。

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

this expression: 这个表达式:

"%[a-zA-Z ]s" 

should be: 应该:

"%[a-zA-Z ]"

Notice no trailing 's'`. 注意没有尾随的“ s”`。

However, this will stop input at any character that is not alphabetic (like a space, or punctuation or newline or digit. ) 但是,这将停止输入任何非字母的字符(例如空格,标点符号或换行符或数字)。

If wanting to input everything on a line, use a format string like: 如果要在一行上输入所有内容,请使用如下格式的字符串:

"%[^\n]"

If you post some sample input, we can be much more specific with our help. 如果您发布一些示例输入,我们可以在我们的帮助下更加具体。

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

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