我有一个程序要求输入一个字符串 (mystring) 和一个字符 (ch)。然后它从字符串 (mystring) 中删除所有输入的字符 (ch)。例如“abcabc”和char 'a' 那么结果应该是“bcbc”。 - 当我使用 scanf 时,如果字符串没有空格,程序运行良好。如果我输入“abc abc abc”,它只读取和处理前 3 个字母(直到空格)。 然后我被建议使用 gets(mystr);因为它可以读取所有的stirng。但是当我使用 gets 时,结果与输入字符串相同,没有任何反应。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 100
int main(int argc, char *argv[])
{
char mystr[N] ,result[N];
char ch;
int i,k;
k=0;
printf("enter string \n");
//gets(mystr);///////////////////////////
//scanf("%s",&mystr);///////////////////
printf("enter char \n");
scanf("%c",&ch);
scanf("%c",&ch);
for ( i = 0; i <= strlen(mystr); i++ )
{
if (mystr[i] != ch)
{
result[k]=mystr[i];
k++;
}
}
puts(result);
system("pause");
return 0;
}
最佳答案
scanf("%c",&ch);
scanf("%c",&ch);
第二个 scanf
是你的问题。它会拾取您在要删除的字母后输入的换行符(并覆盖 ch
的先前值)。
摆脱它。
请注意,如手册页所述:
Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.
关于C 删除字符串中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7859717/