简体   繁体   English

将scanf与char数组及其大小一起使用

[英]Using scanf with char arrays and their size

I am learning C with Deitel's and Deitel's C programming book. 我正在用Deitel和Deitel的C编程书学习C。 Most of the times, when they use the scanf fucntion, for a char name[20]; 大多数情况下,当他们使用scanf功能时,使用char name[20]; , they usually write: scanf("%19s", name); ,他们通常会这样写道: scanf("%19s", name); , in order to avoid buffer overflow. ,以避免缓冲区溢出。

But what can we do if the length of the array is a symbolic constant, say #define LENGTH 20 . 但是,如果数组的长度是符号常量,例如#define LENGTH 20 ,该怎么办。 Obviously, using scanf("%LENGTHs, name); or even scanf("%"LENGTH"s", name); doesn't really help. 显然,使用scanf("%LENGTHs, name);甚至scanf("%"LENGTH"s", name); scanf("%LENGTHs, name); scanf("%"LENGTH"s", name);并没有真正的帮助。

My problem also applies to the fscanf function, when we have to do with a stream different than stdin . 当我们必须处理不同于stdin的流时,我的问题也适用于fscanf函数。

Like this: 像这样:

#include <stdio.h>

#define STR_(x) #x
#define STR(x) STR_(x)

#define LENGTH 20

int main(void){
    char name[LENGTH+1];

    scanf("%" STR(LENGTH) "s", name);
    puts(name);
    return 0;
}

See Stringification for more information on this. 有关更多信息,请参见字符串化

Is better to use fgets(buffer, sizeof(buffer), stdin) 最好使用fgets(buffer, sizeof(buffer), stdin)

But If you want to use scanf() you can create the format at runtime or 但是,如果要使用scanf(),则可以在运行时创建格式或
re-define LENGTH to be a string; 将LENGTH重新定义为字符串;

#define LENGTH "20"
scanf(" %" LENGTH "[^\n]", name);

Edit: 编辑:

try this: 尝试这个:

#include <stdio.h>
#define LENGTH "10"

int main(void) {
    char name[20];
    scanf(" %" LENGTH "[^\n]", name);
    puts(name);
    return 0;
}

Input: abcdefghijklmnopqrstuvxyz 输入: abcdefghijklmnopqrstuvxyz
Output: abcdefghij 输出: abcdefghij

All the best. 祝一切顺利。

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

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