Jarrod L
Jarrod L

Reputation: 293

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.

Upvotes: 0

Views: 429

Answers (5)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726939

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.

Upvotes: 3

Goofy
Goofy

Reputation: 5397

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.

Upvotes: 1

Ambidextrous
Ambidextrous

Reputation: 820

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?

Upvotes: 0

LihO
LihO

Reputation: 42133

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.

Upvotes: 3

ouah
ouah

Reputation: 145899

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);

Upvotes: 1

Related Questions