在我的C程序中使用scanf而不是fgets和fput?

#include  #include  int isPalindrome( char *str, int length ) { if ( length < 1 ) { return 1; /* no more chars to compare, its a palindrome */ } if ( str[0] == str[length-1] ) /* Are the two ends same? */ { return isPalindrome( str+1, length-2 ); /* continue checking */ } else { return 0; /* comparison failed, not a palindrome */ } } void strToUpper( char *src ) { /* convet to upper case any letter */ while( ( *src = toupper( *src ) ) != '\0' ) { ++src; } } int main( void ) { int result = 0; char str[40] = { '\0' }; printf( "Please type the string to identify Palindrom or not: ", stdout ); fflush( stdout ); fgets( str, sizeof str, stdin ); strToUpper( str ); /* make all letters the same for comparison */ result = isPalindrome( str, ( strlen( str ) - 1 ) ); /* recursive starts here */ if( result == 1 ) { printf( "1" ); } else { printf( "0" ); } getchar(); return 0; } 

我写了这个代码来识别C中的palidromes,但我想使用scanf而不是fputsfgets ,所以我可以理解解决这个问题的另一种方法。

此代码中没有fputs ,只有一次调用fgets

这里的输入方法确实不会影响“解决这个问题的方法”。 它是相同的代码 – 改变一行不会改变很多。 scanf不是一个安全的function。 你可以做scanf("%s", str)fgets更好, fgets推荐。 如果需要在fgets之后分析字符串,可以使用sscanf