簡體   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