Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无限while循环代码正在打印2';你好';s';而不是一个hello,代码从用户那里获取输入来检查字符。如果是n,则循环中断 #包括 int main(){ char ch; 而(1){ ch=getchar(); 如果(ch='n'){ 打破 } printf(“你好”); } }_C_Loops_While Loop_Infinite - Fatal编程技术网

无限while循环代码正在打印2';你好';s';而不是一个hello,代码从用户那里获取输入来检查字符。如果是n,则循环中断 #包括 int main(){ char ch; 而(1){ ch=getchar(); 如果(ch='n'){ 打破 } printf(“你好”); } }

无限while循环代码正在打印2';你好';s';而不是一个hello,代码从用户那里获取输入来检查字符。如果是n,则循环中断 #包括 int main(){ char ch; 而(1){ ch=getchar(); 如果(ch='n'){ 打破 } printf(“你好”); } },c,loops,while-loop,infinite,C,Loops,While Loop,Infinite,Loop正在打印2个hello,而不是1个。虽然循环始终为true并接受来自用户的字符,但如果字符为n,则循环中断,否则它必须打印hello并再次请求用户输入并进行处理。无法理解程序的行为。这是因为当您键入字母时,然后按enter键,即“\n”。因此,使用另一个getchar()来容纳该换行符。 例:- #包括 int main(){ char ch; 而(1){ ch=getchar(); getchar(); 如果(ch='n'){ 打破 } printf(“hello\n”); } } g

Loop正在打印2个hello,而不是1个。虽然循环始终为true并接受来自用户的字符,但如果字符为n,则循环中断,否则它必须打印hello并再次请求用户输入并进行处理。无法理解程序的行为。

这是因为当您键入字母时,然后按enter键,即“
\n
”。因此,使用另一个getchar()来容纳该换行符。 例:-

#包括
int main(){
char ch;
而(1){
ch=getchar();
getchar();
如果(ch='n'){
打破
}
printf(“hello\n”);
}
}
getchar()
只读取一个字符。如果以交互方式输入数据,并键入1个字符后跟换行符,则getchar将读取1个字符加上换行符。1+1=2,所以“hello”打印两次

也许你想要:

#include<stdio.h>
 
int main(){
    char ch;
    while(1){
        ch = getchar();
        getchar();
        if(ch =='n'){
            break;
        }
        printf("hello\n"); 
    }
}
#包括
#包括
int
主(空)
{
int ch;/*getchar()返回一个int*/
而((ch=getchar())!=EOF&&ch!=“n”){
如果(!isspace(ch)){
放置(“你好”);
}
}
返回0;
}

您使用的是什么输入?@Stephen Newell我提供的是除表n以外的任何字符。
echo'an'./loop
为我打印一次。@Pranaylapaneni您按了多少个键?如果只按一个键(例如“a”),程序很可能什么也不做。当您按第二个键(例如“回车”或“回车”)时,程序将同时读取这两个字符。如前所述,您的程序正在打印“hello”以响应“a”和新行。我很确定这将解决您的问题。如果有帮助,请将其标记为已接受。@Siddhant-您的解决方案只打印了一次hello,但当我在%c之前留出空间时,Diogo Vieira也会这样做。需要调查此行为。实际上,空间行为依赖于编译器
#include<stdio.h>
 
int main(){
    char ch;
    while(1){
        ch = getchar();
        getchar();
        if(ch =='n'){
            break;
        }
        printf("hello\n"); 
    }
}
#include <stdio.h>
#include <ctype.h>

int
main(void)
{
        int ch;   /* getchar() returns an int */
        while( (ch = getchar()) != EOF && ch != 'n' ){
                if( ! isspace(ch) ){
                        puts("hello");
                }
        }
        return 0;
}