简体   繁体   中英

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:

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 .

You scan whole line into char array and then you take from this char array only characters that you need.

What you should be really looking for is: Parsing a string

Check strtok function.

Hope this helps.

First half:

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

or first half but modifying line array:

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:

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?

Don't forget to end the new array with a '\\0'. :) Hope that works?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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