简体   繁体   English

Scanf将一个变量分配给C中的两个指针

[英]Scanf to assign one variable to two pointers in C

I want to assign one input from a user to two different pointers (I want to read it as both a float and a char). 我想将一个用户的输入分配给两个不同的指针(我想将其作为浮点数和char读取)。 Anyone have any ideas on how to do this or an easy way to convert from one to the other? 任何人都对如何执行此操作有任何想法,或者有一种简单的方法可以将它们相互转换?

char inputString[MAX_SIZE]; // Your input will be stored here as a string.
float inputFloat;           // Here's where you will have your input as float
float *inputFloatPointer;

inputFloatPointer = &inputFloat; // Do this if you want 2 pointers, as requested

fgets(inputString, MAX_SIZE, stdin); // Read from your input buffer

if ((sscanf(inputString, "%f", inputFloatPointer)) == 1) // Try to parse it as a float
    printf("You read a float.\n");  // If the parsing succeeds, you have your float
else
    printf("This is no float.\n");  // Else the user typed something that's not a float.

well a char has a integer representation, not a float. 一个char具有整数表示形式,而不是浮点数。 You will have to MODIFY the float into a char representation and then cast that into a char. 您将必须将float 修改为char表示形式,然后将其转换为char形式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM