简体   繁体   English

使用scanf的C中的回文,并且没有字符串库函数

[英]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. 此刻此代码甚至无法打印出我输入的字符串。当我从main中删除函数时,它神奇地开始打印。 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. 您要确保显示的任何其他printf调用也是如此。

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. 由于您的循环主体中有return关键字(无条件),因此循环最多执行一次。

Also, neither isQuit nor isPalindrome take input from the user. 同样, isQuitisPalindrome都不从用户isPalindrome获取输入。 This means that even if you were to fix the loop by removing the return statement, it still wouldn't be right; 这意味着,即使你通过删除固定循环return声明,但它仍然是不对的; you'd have an infinite loop of isQuit and isPalindrome being passed the same str that the user got asked for on line 15. 您将有一个无限循环的isQuitisPalindrome通过第15行上用户要求的相同str传递。

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. 除了@paddy的答案中指出的问题外,您要做的就是更改while循环,以不断轮询用户的输入并对其进行操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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