问题描述
我是C语言的新手,目前正在阅读K& R的C编程语言.
今天,我尝试从本书中解决2个简单的练习,但发现我的代码有问题-但我不知道为什么.有人可以帮我吗? THX很多!
PS,我正在使用Microsoft的visual studio 2010进行编码.
问题1:编写程序以将其输入复制到其输出,用一个空格替换一个或多个空格的每个字符串.
我的代码:
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");
}
可以将几个空格换成一个空格,但是我输入的每两个字符都会被省略,而且我也不知道为什么...
Q2:编写程序以将其输入复制到其输出,用\ t替换每个制表符,用\ b替换每个退格键,并用\\替换每个反斜杠.
我的代码:
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");
}
问题是屏幕上的输出字符全部变成笑脸的迹象...我不知道为什么这些字符变成了模仿的面孔,我希望有人能帮助我修改这些代码以使其正常工作.
对不起我的英语真的很差----我不是一个母语的人...
THX为您提供帮助!
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!
推荐答案
void main()
{
struct
{
static int space(TCHAR c){ return (' '==c)||('\t'==c)||('\r'==c)||('\n'==c); }
static int escape(TCHAR c){ return ('\t'==c)||('\b'==c)||('\\'==c); }
} is;
TCHAR c;
int s = 0;
// Q1: solution
while('\x1a'/*ctrl+z*/!=(c=_gettch()))
{
if(is.space(c))
{
if(0==s++) _puttchar(' ');
}
else
{
_puttchar(c);
s = 0;
}
}
// Q2: solution
while('\x1a'/*ctrl+z*/!=(c=_gettch()))
{
if(is.escape(c))
{
_puttchar('\\');
_puttchar('\\');
}
else
{
_puttchar(c);
}
}
}
问候.
Regards.
while ((c=getchar())!=EOF)
{
if ((c=getchar())!=' ')
{
...
}
else ...;
}
这篇关于这怎么了整天都无法解决...的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!