简体   繁体   English

使用sprintf制作格式字符串

[英]Making Format String with sprintf

I want to create a format string that will be used in scanf by specifying a MAX_LENGTH for a string input. 我想通过为字符串输入指定MAX_LENGTH来创建将在scanf使用的格式字符串。 What I have is the following but the compiler says it's wrong: 我有以下内容,但编译器说这是错误的:

const int MAX_LENGTH = 50;
char format[9];

sprintf(format, "\%%d[^\n]s", MAX_LENGTH);

The compiler says that the data argument is not used by the format string. 编译器说格式字符串不使用data参数。 The first % should be escaped, and the second one is part of the %d which should be read in from MAX_LENGTH . 第一个%应该被转义,第二个应该是%d一部分,应该从MAX_LENGTH读入。 How do I accomplish this? 我该如何做到这一点? By the way, the format string should read at most MAX_LENGTH characters until a newline is reached. 顺便说一下,格式字符串应该读取最多MAX_LENGTH字符,直到达到换行符。

应使用%%而非 \\%来转义%符号。

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

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