我想制作使用指针删除文本中所有数字的程序,例如当键盘输入是“ab1c9”时,程序结果仅是“abc”。所以我实际上考虑使用指针并使用没有数字结果的单词覆盖它,但它似乎不起作用:/并且我仍然对何时应该使用 * 或不使用 * 感到困惑
这个程序逻辑正确吗?.?
#include <stdio.h>
#include <stdlib.h>
void deldigit(char* str) {
int count = 0;
while(*str != '\0') {
if(*str >= '1' && *str <= '9')
count++;
else
*(str - count) = *str; /* want this *str after increment to overwrite *(str-count) */
str++;
}
*(str - count) = '\0';
printf("%s", str);
}
int main() {
char str[100];
printf("inset word");
scanf("%s", &str);
deldigit(str);
return 0;
}
最佳答案
您需要在循环后倒回 str
,并且您不会删除字符串中的零,请更改为:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void deldigit(char *str)
{
char *res = str;
int count = 0;
while (*str != '\0') {
if (isdigit((unsigned char)*str)) {
count++;
} else {
*(str - count) = *str;
}
str++;
}
*(str - count) = '\0';
printf("%s", res);
}
int main(void)
{
char str[100];
char *ptr;
printf("insert word: ");
if (fgets(str, sizeof str, stdin)) {
if ((ptr = strchr(str, '\n'))) {
*ptr = '\0';
}
deldigit(str);
}
return 0;
}
切换到fgets
以避免缓冲区溢出。
关于c - 编写从文本中删除所有数字的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44225365/