gpt4 book ai didi

c++ - EOF 和 GETCHAR 结束循环

转载 作者:行者123 更新时间:2023-11-30 19:42:12 24 4
gpt4 key购买 nike

我是 C 编程语言新手。我有一个问题如何在 Windows 中结束循环。

#include<stdio.h>
#include<conio.h>

int main() {
printf("enter ur palindrome");
int i[100], c, d = 0, n = 0;

c = getchar();
while (c != '\n') {
i[d] = c;
d++;
}
loop:
while (d != 0) {
if ((i[0 + n] != i[d - n])) {
n++;
goto loop;
}

printf("this is not a palindrome");

break;
}
printf("this is a palindrome");

return (0);
}

我几乎尝试了所有 CTRL+Z、CTRL+C、CTRL+D,用 EOF 替换 '\n'还有更多的事情。没有什么对我有用。我在 Windows 10 上使用 CodeBlocks。除了 getchar 和 eof 之外,还有其他方法可以编写此类程序吗?

最佳答案

不要使用goto,而是使用continue;来重复循环。

但是,所发布的代码还存在许多其他问题。

The array `int i[100]` is never terminated with a NUL byte ('\0')
An array of char not int should be used.
this loop: `while (d != 0) will never exit,
because (if the loop is ever entered)
the `d` variable is never changed within the loop

这是我建议的代码:

警告:未经过彻底测试

#include <stdio.h>
//#include<conio.h> <-- not used, so do not include
#include <string.h>

#define MAX_LENGTH (100)

int main( void )
{
int d;
int n;
char i[MAX_LENGTH];

printf("enter ur palindrome\n"); // <-- \n so will immediately print

if ( NULL != fgets( i, MAX_LENGTH, stdin ) )
{
if( strlen( "\n" ) < strlen( i ) )
{ // then, some string entered

// remove any trailing '\n'
char *newline = strstr( i, "\n" );
if( newline )
{ // then '\n' found
*newline = '\0';
} // end if

d = strlen( i );
for( n=0; (d-n) >= n; n++ )
{

if( i[0 + n] != i[d - n] )
{ // then no match
printf("this is not a palindrome");
break;
} // end if
} // end for

if( (d-n) < n )
{ // then palindrome
printf("this is a palindrome");
} // end if
}

else
{
printf( "nothing entered\n");
} // end if
} // end if

return (0);
} // end function: main

关于c++ - EOF 和 GETCHAR 结束循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32676767/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com