简体   繁体   English

在C语言中,您如何只扫描输入行的一半?

[英]In C, how do you scan only half of a line of input?

Simple question (I think), in C, I was able to scan in an entire line using: 一个简单的问题(我认为),在C语言中,我能够使用以下命令扫描整行:

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. 例如,在什么地方打印“请把我切成两半”,如何只将“我切成两半”,包括空格。

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 . 上面的代码就是这样工作的: strlen确定整个字符串的长度(21),然后我们使用整数除法(10)将其分成两半,将其添加到行首的指针,然后将结果传递给printf

You scan whole line into char array and then you take from this char array only characters that you need. 您将整个行扫描到char数组中,然后从此char数组中仅提取所需的字符。

What you should be really looking for is: Parsing a string 您真正要寻找的是: 解析字符串

Check strtok function. 检查strtok功能。

Hope this helps. 希望这可以帮助。

First half: 上半场:

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

or first half but modifying line array: 或上半部分,但修改line阵:

line[strlen(line) / 2] = '\0';
printf("%s\n", line);

Second half: 下半场:

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

line is an array, so you can use pointer arithmetic: line是一个数组,因此可以使用指针算法:

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

You "move" the beginning point from which string is displayed. 您“移动”显示字符串的起点。

strlen(line) should give you the length of the line, then you can use a char array of half that length, iterate over the original line that many times, and copy character by character? strlen(line)应该给您行的长度,然后您可以使用长度的一半的char数组,遍历原始行很多次,然后逐个字符地复制?

Don't forget to end the new array with a '\\0'. 不要忘记以'\\ 0'结尾新数组。 :) Hope that works? :)希望行得通吗?

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

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