scanf /字段长度:使用变量/宏,C / C ++ [英] scanf / field lengths : using a variable / macro, C/C++

查看:87
本文介绍了scanf /字段长度:使用变量/宏,C / C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用scanf时,如何使用变量指定字段长度。
例如:

 字符单词[20 + 1]; 
scanf(file,%20s,word);

此外,使用20 + 1是否正确(因为需要在上加上\0结束?)。相反,我想输入以下内容:

  #define MAX_STRING_LENGTH 20 

,然后

 字符词[MAX_STRING_LENGTH + 1 ]; 
scanf(file,% MAX_STRING_LENGTH s,word); //这里的正确语法是什么?

这可能吗?

  int length = 20; 
个字符[length + 1];
scanf(file,%长度%s,word); //这里的正确语法是什么?

谢谢。

解决方案

对于第一种情况,以下内容应满足您的需求。

  #define MAX_STRING_LENGTH 20 
#define STRINGIFY(x)STRINGIFY2(x)
#define STRINGIFY2(x)#x

{
...
char word [MAX_STRING_LENGTH + 1];
scanf(file,% STRINGIFY(MAX_STRING_LENGTH) s,单词);
...
}

注意:需要两个宏,因为如果您尝试直接使用类似STRINGIFY2之类的方法,您只会得到字符串 MAX_STRING_LENGTH 而不是其值。



在第二种情况下,您可以使用诸如snprintf之类的东西,并且至少某些C版本仅允许您使用 malloc()或类似的方式在堆中分配动态大小的数组。 / p>

How can I use a variable to specify the field length when using scanf. For example:

char word[20+1];
scanf(file, "%20s", word);

Also, is it correct to use 20+1 (since it needs to add a \0 at the end?). Instead, I'd like to have something like:

#define MAX_STRING_LENGTH 20

and then

char word[MAX_STRING_LENGTH+1];
scanf(file, "%"MAX_STRING_LENGTH"s", word); // what's the correct syntax here..?

Is this possible? How about if it's a variable like:

int length = 20;
char word[length+1];
scanf(file, "%" length "%s", word); // what's the correct syntax here..?

Thanks.

解决方案

The following should do what you need for the first case.

#define MAX_STRING_LENGTH 20
#define STRINGIFY(x) STRINGIFY2(x)
#define STRINGIFY2(x) #x

{
  ...
  char word[MAX_STRING_LENGTH+1];     
  scanf(file, "%" STRINGIFY(MAX_STRING_LENGTH) "s", word);
  ...
}

NOTE: Two macros are required because if you tried to use something like STRINGIFY2 directly you would just get the string "MAX_STRING_LENGTH" instead of its value.

For the second case you could use something like snprintf, and at least some versions of C will only let you allocate dynamically sized arrays in the heap with malloc() or some such.

这篇关于scanf /字段长度:使用变量/宏,C / C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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