bry*_*nph 1 c spaces counting cpu-word
我想知道为什么下面的代码不能像下面的代码那样工作.代码应该做的是删除多个连续的空格并只显示一个空格:所以"它的工作原理"变成"它的工作原理".第一段代码就像"它的工作原理"一样.
不行
#include <stdio.h>
main(){
int c;
int lastspace;
lastspace = 0;
while((c = getchar()) != EOF){
if(c != ' ')
putchar(c);
lastspace = 0;
if(c == ' '){
if(lastspace == 0){
lastspace = 1;
putchar(c);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
作品
#include <stdio.h>
main(){
int c
int lastspace;
lastspace = 0;
while((c = getchar()) != EOF){
if(c != ' ')
putchar(c);
if(c == ' '){
if(lastspace != c){
lastspace = c;
putchar(c);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
在你的第一个例子中
if(c != ' ')
putchar(c);
lastspace = 0;
Run Code Online (Sandbox Code Playgroud)
不会{}在if语句后面放置大括号,因此只有有条件执行紧接的后续语句.更改缩进和添加大括号表明代码实际上是
if(c != ' ') {
putchar(c);
}
lastspace = 0;
Run Code Online (Sandbox Code Playgroud)
这就是为什么某些编码标准要求使用{}遵循所有控制语句的原因.
| 归档时间: |
|
| 查看次数: |
154 次 |
| 最近记录: |