如何允许char或integer存储在同一变量中?像允许在该变量中扫描char和int一样. [英] How can I allow to char or integer getting stored in same variable? Like allow scanning of char and int in that variable.

查看:180
本文介绍了如何允许char或integer存储在同一变量中?像允许在该变量中扫描char和int一样.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include< stdio.h>
main(){
int n;
printf(输入整数或字符");
scanf(%__",& n); //我想允许将字符存储在此变量n中.
}

#include<stdio.h>
main(){
int n;
printf("Enter a integer or character");
scanf("%__", &n); // I want to allow to characters to be stored in this variable n.
}

推荐答案

将其扫描为字符串,然后决定如何处理.
这意味着创建一个char数组以传递给scanf,并读取字符串.
然后,您可以查看它,并确定用户输入的是单个字符还是数字.在后一种情况下,您可以将其转换为整数并将其存储在适当的变量中.
Scan it as a string, and then decide what to do with it afterwards.
That means creating a char array to pass to scanf, and reading the string.
You can then look at it, and decide if the user entered a single character, or a number. In the later case, you can then convert that to an integer and store it in teh appropriate variable.
char myString[256];
scanf("%s", myString);


会阅读,其余的取决于您!
但是...这可能不是一个好主意.考虑一下:如果您输入"A",则显然是他想要的字符.如果他输入"123",则为整数.但是,如果他键入"7"怎么办?是字符(是)还是整数(是)?您不一定可以从用户输入的内容中推断出用户的意图! :laugh:


will read it, the rest is up to you!
But...this probably isn''t a good idea. Think about it: if the your types "A" it''s obviously a character he wanted. If he types "123" then it''s an integer. But what if he types "7"? is that a character (yes) or an integer (yes)? You can''t necessarily infer the user''s intent from what he typed! :laugh:


这篇关于如何允许char或integer存储在同一变量中?像允许在该变量中扫描char和int一样.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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