I am a totally newcomer to C and I am currently reading K&R's The C Programming Language.
Today I try to solve 2 simple exercises from this book and I found something wrong with my code----but I don't know why. Could anybody help me about them? THX alot!
PS, I am using Microsoft's visual studio 2010 to code.
Q1: write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.
my code:
#include <stdio.h>
#include <stdlib.h>
#define OUT 0
#define IN 1
main()
{
int c, state;
state=IN;
printf("This is a minyfunction designed to omit blanks you typed in into one blank\n");
printf("Please type in 'Control + Z ' in a new line when you have finished typing\n");
while ((c=getchar())!=EOF)
{
if ((c=getchar())!=' ')
{
if (state==OUT)
{
printf(" ");
state=IN;
putchar(c);
}
else putchar(c);
}
else state=OUT;
}
system("Pause");
}
The exchange from several blanks into one blank works out okay, but for every two characters I type in, one of them will be omitted and I don't know why...
Q2: Write a program to copy its input to its output, replacing each tab by \t, each backspace by \b, and each backslash by \\.
my code:
#include <stdio.h>
main()
{
int c;
while ((c=getchar()!=EOF))
{
if (c==' ')
{
printf("\\n");
}
else if (c=='\t')
{
printf("\\t");
}
else if (c=='\n')
{
printf("\\n");
}
else if (c=='\\')
{
printf("\\");
}
else
putchar(c);
}
system("Pause");
}
The problem is that the output characters on screen all turn to be signs of smiling faces...I don't know why these characters become similing faces and I hope anybody could help me to revise these code to make it work out okay.
Sorry about my really poor English----I am not a native speaker...
THX for your help!