c - C中的空间缩减
问题描述
我有一个任务说'重写输入的文本并将多个空格减少到只有一个空格'。我编写的程序会重写单个单词,但在我输入一个空格后完全停止工作。
#include <stdio.h>
int main()
{
int t,c,state;
state=1;
while((c=getchar())!=EOF)
{
if(c==' ')
state=0;
if (state==0)
{
while(c=' ')
state=0;
putchar(' ');
putchar(c);
state=1;
}
else putchar(c);
}
}
解决方案
你的代码是错误的。您试图制造一台基本上是正确方法的 staet 机器,但您失败了,因为这些行存在两个问题:
while(c=' ')
state=0;
首先你肯定想写while(c == ' ')
,你的编译器可能警告过你。
但即使这是错误的:
while(c == ' ')
state=0;
如果条件c == ' '
为真,此循环将永远不会结束。
你需要的是这样的:
#include <stdio.h>
int main(void) {
int c;
int spaceread = 1;
while ((c = getchar()) != EOF) {
if (c != ' ')
spaceread = 0; // something else than space => process normally
else
{
// space char has been read
if (spaceread) // if a space has been read previously => do nothing,
continue; // just continue to read the next character.
spaceread = 1; // remember we've read a space
}
putchar(c); // print character
}
}
推荐阅读
- assembly - 如何在 xtensa 架构中映射重置向量?
- python - 如何使用 Djano、Ajax 和 javascript 发送具有多个动态表单 ID 的数据?
- algorithm - 用 if 语句求运行时间的期望值
- javascript - 如何用关闭图标关闭汉堡菜单
- java - 如何检查数据是否为映射(键值对)?
- reactjs - React.lazy 会提高 React Native 的性能吗?
- jquery - 使用 Jquery datepicker 添加自定义按钮
- javascript - .then() callback doesn't wait for the first promise to be triggered
- git - 使用子模块签出 git 存储库时出错
- blueprism - 通过 BluePrism 登录网站时出现身份验证错误