使用scanf函数,而不是fgets和的fputs在我的C程序? [英] Use scanf instead of fgets and fputs in my program in C?

查看:100
本文介绍了使用scanf函数,而不是fgets和的fputs在我的C程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
#include <ctype.h>

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;

 }

我写这篇code标识用C palidromes,但我想用 scanf函数而不是的fputs 与fgets ,这样我就可以了解对方的方式来解决这个问题。

I wrote this code which identifies palidromes in C, but I want to use scanf instead of fputs or fgets, so I can understand the other way to solve this problem.

推荐答案

有没有的fputs ,只为一个单一的通话与fgets 在这个code。

There is no fputs and only a single call to fgets in this code.

输入的方法,在这里真的没有影响的方式来解决这个问题。这是相同的code - 改变一个行会不会改变很多。 scanf函数不是一个安全的功能。你可以做 scanf函数(%S,STR),但与fgets 较好,推荐使用。如果你需要在与fgets 来分析字符串,可以使用的sscanf

The method of input here really don't affect "way to solve this problem". It's the same code - changing one line won't change lot. scanf not a safe function. You can do scanf("%s", str) but fgets is better and recommended. If you need to analyze string after fgets, you can use sscanf.

这篇关于使用scanf函数,而不是fgets和的fputs在我的C程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆