【问题标题】:How is it working : a specific while-loop它是如何工作的:一个特定的while循环
【发布时间】:2019-05-04 04:41:54
【问题描述】:
int main(){ 
char s;
    while(s!='\n'){
        scanf("%c",&s);
        if(s==' ')continue;
        else printf("%c",s);
    }
}

输入:堆栈溢出

输出:堆栈溢出

我所期望的: SSttaackkkoovveerrfflloooww

我不明白这是怎么回事。

【问题讨论】:

  • 这是未定义的行为,因为 s 未初始化。除此之外,循环似乎只是按字符扫描输入字符并跳过空格。你应该解释为什么你期望这个输出。
  • 您看到本地回声了吗?
  • 缓冲,我敢打赌。默认情况下,输出到stdoutprintf 写入)是 line buffered,这意味着它不会实际写入控制台,除非缓冲区已满或有换行符。尝试明确地flushingstdout
  • 因为我打印字符。
  • 我怎样才能到达这个缓冲区

标签: c loops while-loop


【解决方案1】:
- You have a while loop with the condition that s is not an enter character.
- You read a character from keyboard
- You test if the character is space.
- If true (the character is space) you continue reading another character
  • 如果为 false(字符不是空格),则将其打印在屏幕上(仅打印一个字符)

  • 您的代码中没有一行打印出您存储在 s 中的字符的两倍 例如。否则 printf("%c%c",s,s);

【讨论】:

    猜你喜欢
    • 2012-05-17
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 2016-09-27
    相关资源
    最近更新 更多