Hey there guys,
I am new to C programming and even newer to this forum. I am trying to teach my self C programming basics in preparation for when I take the unit at uni for my second semester.
I am currently working my way through " "The C Programming Language", 2nd edition, Kernighan and Ritchie" and am getting a little stuck on some of the exercises, namely Ex 9 "Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank."
My first issue was actually understanding what the question was asking of me What I thought the question was asking is that if you input a string of characters and there happened to be more than one space together then it would remove the extra spaces and just have one space. so the input "My____name____is____David" would be output as "My_name_is_David"
After going to the website http://users.powernet.co.uk/eton/kandr2/krx1.html and looking at the exercise answers I copied and compiled the code below, however the output was not what i expected. The program takes the input and then doubles any spaces in that input. So "My__name__is__David" ends up being output as "My____name____is____David"
I was just wanting to know anyones opinion on this, have I misunderstood the question ?
The other point that I would like to get clarified is that I cant understand how the integer "inspace" interacts with the rest of the program. All I see is that "inspace" is either equal to 0 or 1. I do not understand how this integer manages to double the number of spaces in the output. If someone could just break it down for me and explain it step by step I may be able to understand it a little better.
Any help would be greatly appreciated !!
Thanks
Trev
Code:
#include <stdio.h>
int main(void)
{
int c;
int inspace;
inspace = 0;
while((c = getchar()) != EOF)
{
if(c == ' ')
{
if(inspace == 0)
{
inspace = 1;
putchar(c);
}
}
/* We haven't met 'else' yet, so we have to be a little clumsy */
if(c != ' ')
{
inspace = 0;
putchar(c);
}
}
return 0;
}