此解決方案適用于 C 編程語言書籍中的 1-12 練習。問題是撰寫一個程式,每行列印一個單詞的輸入。
我找到了以下解決方案:
#include <stdio.h>
int main(void)
{
int c;
int inspace;
inspace = 0;
while((c = getchar()) != EOF)
{
if(c == ' ' || c == '\t' || c == '\n')
{
if(inspace == 0)
{
inspace = 1;
putchar('\n');
}
/* else, don't print anything */
}
else
{
inspace = 0;
putchar(c);
}
}
return 0;
}
有人可以解釋為什么在 if 引數中使用 inspace == 0 以及邏輯稍后在陳述句中如何使用 inspace = 1 嗎?
0是否表示輸入中的空格?
uj5u.com熱心網友回復:
舊版本的 C 沒有“真”和“假”的布爾資料型別。
相反,他們只是使用整數并決定這0意味著“假”,其他任何東西都意味著“真”。
考慮到這一點,上面代碼的一部分可以這樣讀:
if(c == ' ' || c == '\t' || c == '\n')
{
if(inspace == FALSE)
{
inspace = TRUE;
putchar('\n');
}
/* else, don't print anything */
}
else
{
inspace = FALSE;
putchar(c);
}
本質上,邏輯是這樣的:
如果下一個字符是非空白字符 ( ) 之后的第一個空白字符,則
inspace == FALSE列印換行符否則,如果下一個字符只是現有空白 (
inspace == TRUE) 中的更多空白,則忽略它否則列印它
uj5u.com熱心網友回復:
演算法缺陷
雖然比較可能會有一些混淆,但存在演算法缺陷。讓我們先處理這個。
應該inspace = 1;在回圈之前使用。
if (!inspace) putchar('\n');在回圈之后添加。
關于使用 2-state 變數時的比較inspace
- 使用
<stdbool.h>。它自 1999 年以來一直可用。 - 代碼
inspace作為 abool而不是int. - 放下
==,!=。
不要像abd == true或那樣編碼def == false。不要創建TRUE或FALSE。
#include <stdbool.h>
#include <stdio.h>
int main(void) {
int c;
bool inspace = true; // Note this is the opposite state of OP's code.
while((c = getchar()) != EOF) {
if(c == ' ' || c == '\t' || c == '\n') {
if(!inspace) {
inspace = true;
putchar('\n');
}
/* else, don't print anything */
}
else {
inspace = false;
putchar(c);
}
}
if (!inspace) {
putchar('\n');
}
return 0;
}
其他改進
利用<ctype.h>
// if(c == ' ' || c == '\t' || c == '\n')
if (isspace(c)) // For all white-spaces, not just 3 of them.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/537925.html
標籤:Cif语句
