简体   繁体   中英

Palindrome in C using scanf and no string library functions

the assignment is to get an input string, and using no string library functions to be able to handle the string. this code at the moment doesn't even print out the string i get in. when I remove the functions from main it magically starts to print. any help would be greatly appreciated

    #include <stdio.h>
#include <string.h>

#define SIZE 32

int isQuit(char str[]);
void isPalindrome(char str[]);


int main (){
    int cont = 0;
   char str[SIZE];
   fflush(stdin);
   printf("please enter a word:\n");
   scanf("%s\n", str);
   printf("%s\n", str);

  while(cont == 0)
  {
    scanf("%s\n", str);
   printf("%s\n", str);
     cont =  isQuit(str);
    isPalindrome(str);
  }
   return 0;
}

You most likely are suffering from line buffering in your terminal. Until you write a newline character, any characters written are not displayed.

Try adding a newline when displaying your input:

printf("%s\n", str);

The same goes for any other printf calls you do that you want to ensure are displayed.

By the way, your null-termination test is incorrect. The escape character is \\ , not / . Change your loop to:

while (str[h] != '\0')

Or simply:

while (str[h])

There are a few things wrong with your code here:

while(isQuit(str) == 0)
{ 
    isPalindrome(str);
    return 0 ;
}

Since you have the return keyword in your loop body (unconditionally), the loop will execute at most one time.

Also, neither isQuit nor isPalindrome take input from the user. This means that even if you were to fix the loop by removing the return statement, it still wouldn't be right; you'd have an infinite loop of isQuit and isPalindrome being passed the same str that the user got asked for on line 15.

What you have to do is change your while loop to continually poll the user for input and act upon it, in addition to the issues pointed out in @paddy's answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM