几个问题:
永远永远永远永远永远永远使用gets
。首先,它从C99开始不再使用,并且将从标准的下一版本中消失。其次,它将在你的代码中引入了一个故障点(不是可能是介绍,会介绍)。改为使用fgets(str, sizeof str, stdin)
代替gets(str)
。
使用字符常量,而不是数值,因为所有的世界不是ASCII:
if (str[i] == ' ') // not str[i] == 32
空白包括标签,换页,返回等,而不仅仅是空间;而不是检查单个值,请使用库函数isspace()
。
以下行是一个问题:
str[i++] = str[i];
str[i] = str[i++];
首先,这应该调用未定义的行为;您正试图在序列点之间多次读取和更新一个对象。其次,我不确定这个逻辑。看起来你正在尝试交换元素,而不是仅仅跳过一个元素。
你传递一个整数值到strlen
:这是行不通的。它会将该整数值解释为一个地址(至少应该得到一个警告),结果可能不好。
您可以在一个循环有两个数组索引做到这一点:
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char str[15];
if (fgets(str, sizeof str, stdin) != NULL)
{
size_t r, w;
printf("Original: \"%s\"\n", str);
/**
* str[r] is the element that we are reading; str[w]
* is the element that we are writing
*/
for (r = 0, w = 0; str[r] != 0; r++)
{
if (!isspace(str[r])) // if str[r] is not a whitespace character
str[w++] = str[r]; // write it to str[w]; note that we only
// advance w for non-whitespace chars
}
str[w] = 0; // add the 0 terminator at the end
printf("Stripped: \"%s\"\n", str);
}
return 0;
}
显然,这改变了原来的字符串。如果由于某种原因需要保留原始输入,则必须声明第二个缓冲区来保存修改过的字符串。
哪些您发布的当前代码的缺点? – 2011-03-31 14:35:34
它没有工作。 str [strlen(i)] ='\ 0';将str [strlen(str)] ='\ 0'; – yEL155 2011-03-31 14:37:29
作业?没问题,如果是这样,只需用标记标记,以便得到更好的答案 – pmg 2011-03-31 14:50:37