C 编程 - 限制用户输入一定数量的字符 [英] C Programming - Limit user to type certain amount of characters

查看:63
本文介绍了C 编程 - 限制用户输入一定数量的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我开始这个程序,这是一个新的学习阶段,我需要学习如何在我提示用户输入时只允许用户输入一定数量的字符.例如:

So I'm starting this program, new stage of learning and I need to learn how to only allow the user to input a certain amount of characters when I prompt them to type. So for example:

char firstname[20];
printf("What is your first name?");
scanf("%s", &firstname);

我只希望用户能够键入和输入 20 个字符.我将如何解决这个问题,并且在提示用户仅输入数字时是否会采用相同的方式?

I only want the user to be able to type and enter 20 characters. How would I go about this and would it be the same way when prompting the user to only enter numbers?

推荐答案

我只希望用户能够输入和输入 20 个字符

好吧,您只能指导用户并期望他们遵循.您无法阻止用户输入超过 n 个字符,但是,以编程方式,您只能将扫描限制为 n字符,使用

Well, you can only instruct the user and expect them to follow. There is nothing you can do to stop the user from inputting more than n characters, but, programatically, you can only limit the scanning to n characters, using

char firstname[20];
printf("What is your first name?");
scanf("%19s", firstname);           //& not needed

为空终止符留出空间.

如果 name 包含空格,%sscanf() 将无法处理输入.在这种情况下,您可能需要使用 fgets() 可以处理输入字符串中是否存在空格.

In case, the name contains a whitespace, %s with scanf() will not be able to handle the input. In that case, you may want to make use of fgets() which can handle the presence of whitespace in the input string.

就是说,

  1. 您可能希望在扫描后清理剩余字符的输入缓冲区.
  2. 始终检查 scanf() 的返回值以确保扫描成功.
  1. You may want to clean up the input buffer of remaining characters after scanning.
  2. Always check for the return value of scanf() to ensure successful scanning.

这篇关于C 编程 - 限制用户输入一定数量的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆