scanf 接收 空格 输入_如何允许使用scanf输入空格?
人們(尤其是初學者)不應該使用scanf(“%s”)或gets()或任何其他沒有緩沖區溢出保護的函數,除非你確定輸入總是一個特定的格式甚至不是)。
記住,scanf代表“掃描格式化”,并且珍貴的格式比用戶輸入的數據少。如果您對輸入數據格式具有完全控制權,但通常不適合用戶輸入,則這是最理想的選擇。
使用fgets()(它有緩沖區溢出保護)來獲取你的輸入一個字符串和sscanf()來評估它。因為你只想要用戶輸入而不解析,你不需要真正需要sscanf()在這種情況下:
#include
#include
#include
/* Maximum name size + 1. */
#define MAX_NAME_SZ 256
int main(int argC, char *argV[]) {
/* Allocate memory and check if okay. */
char *name = malloc (MAX_NAME_SZ);
if (name == NULL) {
printf ("No memory\n");
return 1;
}
/* Ask user for name. */
printf("What is your name? ");
/* Get the name, with size limit. */
fgets (name, MAX_NAME_SZ, stdin);
/* Remove trailing newline, if there. */
if ((strlen(name)>0) && (name[strlen (name) - 1] == '\n'))
name[strlen (name) - 1] = '\0';
/* Say hello. */
printf("Hello %s. Nice to meet you.\n", name);
/* Free memory and exit. */
free (name);
return 0;
}
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的scanf 接收 空格 输入_如何允许使用scanf输入空格?的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: ab plc编程软件_三菱PLC编程程序
- 下一篇: monkey测试_爱码小士丨 APP稳定
