[英]EOF AND GETCHAR to end loop
我是 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 之外,还有其他方法可以编写此类程序吗?
你可能想再看看这个部分
c=getchar();
while(c!= '\n') // Value of c never altered, hence it'll never break
{ i[d]=c;
d++;
}
是的,另一个循环
loop: // not required
while ( d!=0 ) // can't see change in d within this body, is it n ?
{
if((i[0+n] != i[d-n]))
{
n++;
goto loop; // not required
continue; //will do
}
printf("this is not a palindrome");
break;
}
你实际上会收到一条额外的消息说
this is a palindrome
印刷后
this is a not palindrome
我想这不是你想要的。
在该循环中,您需要再次读取下一个字符,因此需要在该循环中添加getchar()
c=getchar();
while(c!= '\n')
{
i[d]=c;
d++;
c=getchar();
}
这是编写那段代码的另一种方式
#include <stdio.h>
#include <string.h>
int main()
{
char *word;
int i;
int n;
printf( "enter ur palindrome" );
scanf("%[^\n]", word); // reads input all the way to the new line
n = strlen( word );
for ( i = 0; i < n; i++ ) {
if ( word[ i ] != word[ n-1 - i ] ) {
break; /* for */
}
}
if ( i == n ) {
printf( "This is a palindrome");
} else {
printf( "This is not a palindrome" );
}
return 0;
}
而不是使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.