C语言 如何打印有限数量的字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2641903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:10:52  来源:igfitidea点击:

How do you print a limited number of characters?

cstringformattingprintf

提问by Mike Pateras

Sorry to put a post up about something so simple, but I don't see what I'm doing wrong here.

很抱歉就这么简单的事情发表一篇文章,但我不明白我在这里做错了什么。

char data[1024];
DWORD numRead;

ReadFile(handle, data, 1024, &numRead, NULL);

if (numRead > 0)
    printf(data, "%.5s");

My intention with the above is to read data from a file, and then only print out 5 characters. However, it prints out all 1024 characters, which is contrary to what I'm reading here. The goal, of course, is to do something like:

我上面的意图是从文件中读取数据,然后只打印出 5 个字符。但是,它打印出所有 1024 个字符,这与我在这里阅读的内容相反。当然,目标是执行以下操作:

printf(data, "%.*s", numRead);

What am I doing wrong here?

我在这里做错了什么?

回答by R Samuel Klatchko

You have your parameters in the wrong order. The should be written:

您的参数顺序错误。应该写成:

printf("%.5s", data);

printf("%.*s", numRead, data);

The first parameter to printfis the format specifier followed by all the arguments (which depend on your specifier).

第一个参数printf是格式说明符,后跟所有参数(取决于您的说明符)。

回答by AraK

I think you are switching the order of arguments to printf:

我认为您正在将参数顺序切换为printf

printf("%.5s", data); // formatting string is the first parameter

回答by Brian Roach

You're not calling printf() correctly.

您没有正确调用 printf()。

int printf ( const char * format, ... );

Which means...

意思是...

printf("%.5s", data);

回答by sjchoi

You are using wrong syntax for the printfstatement, and the .number is only for numerical variables.

您对printf语句使用了错误的语法,并且 .number 仅用于数字变量。

So it should be

所以应该是

int i;
for(i=0;i<5;i++)
   printf("%c", data[i]);