使用_flushall()修复了我的代码,我不明白为什么

时间:2017-01-31 01:37:50

标签: c string visual-studio buffer

我编写了一个从字符串中删除给定char的函数。

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

char* input_long(void);
void removeChar(char str[], char ch);

void main()
{       
 char *str, ch;

 str=input_long();
 printf("\nplease enter a char to be removed from the string: ");
 scanf("%c", &ch);

 removeChar(str, ch);
 printf("the string after the removal is %s \n", str);

 free(str);
}

void removeChar(char str[], char ch) //this function removing a given char from a given string//
{
 int i,j = 0;
 for (i = 0; str[i] != '\0'; i++) //looping the string until its end//
     {
     if (str[i] != ch) //by that we ensure the char will be erased from the string //
      {
       str[j] = str[i];
       j++;
      }
     }
  str[j]='\0';   //the end of the new string after the whole process//
}

char* input_long(void) //this function gets a string dynamically allocated//
{
 char tempstr[80], *str;

 printf("enter a string\n");
 gets(tempstr);
 str=(char*)malloc((strlen(tempstr)+1)*sizeof(char));
 strcpy(str,tempstr);

 return str;
}

我的代码运行不顺利;当我运行它时,它似乎引导了要求用户输入字符串的语句。我通过添加_flushall()修复了代码,现在代码运行良好:

_flushall
 str=input_long();
 printf("\nplease enter a char to be removed from the string: ");
 scanf("%c", &ch);

我真的不明白为什么添加该语句确实修复了它。

0 个答案:

没有答案