【问题标题】:While loop printing and scanf [duplicate]While循环打印和scanf [重复]
【发布时间】:2016-10-08 16:14:47
【问题描述】:

这个值的程序: ABCDEF 一开始没问题

但是当你输入一个带有空格的值时,比如: ABC DEF 程序运行错误!!!! while 循环第二次忽略 scanf 我做错了什么?!

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main(){
    bool checkSrc = false;
    bool checkDst = false;

    while (!checkSrc && !checkDst)

    {

    char ins[10];

    printf("White Player : ");
    scanf("%s",&ins);

    }

}

【问题讨论】:

  • scanf 格式 "%s" 读取 空格分隔“单词”。
  • @user3121023 是的,尽管还需要检查ins[strlen(ins)-1] 处的'\n' 字符。如果不存在,则缓冲区太小,输入行上剩余未读字符。如果它在那里,则缓冲区足够大,您可以对字符串进行进一步操作,例如去除前导和尾随空白字符,包括最后的换行符。

标签: c scanf


【解决方案1】:

%s - 字符串。这将读取后续字符,直到找到空格(空格字符被认为是空白、换行符和制表符)。

我建议您使用fgets() 而不是scanf(),因为后者没有缓冲区溢出保护。

#define namesize 15
char *ins = malloc (namesize);

fgets(ins, namesize, stdin);

【讨论】:

  • ...并注意新行 char '\n',如果有的话,将进入缓冲区 ins
猜你喜欢
  • 2017-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-06
  • 2017-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多