在C中,如何仅扫描一行输入的一半?(In C, how do you scan only half of a line of input?)

编程入门 行业动态 更新时间:2024-10-27 11:27:50
在C中,如何仅扫描一行输入的一半?(In C, how do you scan only half of a line of input?)

简单的问题(我认为),在C中,我能够使用以下方法扫描整行:

fgets(line, MAX, input); printf("%s\n", line);

例如,它会打印出“请把我切成两半”,我怎么只能把“我变成一半”,包括白色空格。

Simple question (I think), in C, I was able to scan in an entire line using:

fgets(line, MAX, input); printf("%s\n", line);

Where it would, for example, print "Please cut me in half", how do I only get "me in half", including white spaces.

最满意答案

在扫描整条线之前,您不知道中间位置。 但你可以扫描整行,然后只打印下半部分,如下所示:

printf("%s\n", line+strlen(line)/2);

这就是上面代码的工作方式: strlen确定整个字符串的长度(21),然后我们用整数除法(10)将它除以一半,将它添加到指向行开头的指针,并将结果传递给printf 。

You do not know where the middle is until you scan the whole line. But you can scan the entire line, and then print only the second half, like this:

printf("%s\n", line+strlen(line)/2);

This is how the above code works: strlen determines the length of the entire string (21), then we divide it in half using integer division (10), add it to the pointer to the beginning of the line, and pass the result to printf.

更多推荐

本文发布于:2023-04-27 11:10:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1327113.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:scan   line   input

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!