C-此代码功能是否功能



这是我在服用CS50时正在编写的代码。我正在用C中的CS50 IDE编写此代码。我想制作它,以便我可以输入一个名称或数字,而无需为每个编写每个代码,但我不知道该怎么做。任何帮助将非常感激。谢谢。

#include<cs50.h>
#include<stdio.h>
int main(void)
{
    printf("Name: n");
    string name1 = get_string();
    if (name1 is in, int name1 = get_int())
    ;
    printf("Nice, %sn", name1);
}

c不本地支持类型的多态性,因此您可以编写处理intchar []的代码,也无法在运行时确定对象的类型。

您可以使用一些技术来伪造它。您可以使用宏或功能指针来创建类型的无形接口,这些接口将特定于类型的操作推迟到其他功能。C11引入了_Generic宏,该宏可允许您根据参数类型选择操作:

#define DO_SOMETHING_WITH( X ) _Generic( (X),                           
                                         int : do_something_with_int,   
                                      char * : do_something_with_string 
                                       )( X )
void do_something_with_int( int arg )
{
  ...
}
void do_something_with_string( const char *arg )
{
  ...
}
int main( void )
{
  int x;
  char y[SOME_LENGTH];
  DO_SOMETHING_WITH( x );
  DO_SOMETHING_WITH( y );
  ...
}

但最后,您仍然必须编写执行特定类型处理的代码。

另外,如果您尝试执行printf("Nice, %sn", name1);,而name1int,则会出现错误。您应该使用printf("Nice, %dn", name1);进行打印整数

最新更新