所以,这是我第一次在这里发帖,我将尝试尽可能具体.我必须为我的学校制作一个程序说:
首先编写一个获取字符并返回的函数:
然后,使用您的函数,创建一个获取字符串的程序,并在函数更改后重新打印它.在用户输入'QUIT'之前,应该继续询问新字符串,在这种情况下,将打印'Bye!' 然后退出
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
char fnChange(char c)
{
if (c > 'a'-1 && c < 'z'+1)
c = c - 32;
else if (c > '0'-1 && c < '9'+1)
c = '\\' ;
else if ( c > 'A'-1 && c < 'Z'+1)
c = c;
else
c = '*';
return c;
}
int main()
{
int i, refPoint;
char *str = (char*)malloc(10);
//without the next one, the program crashes after 3 repeats.
refPoint = str;
while (1==1) {
printf("Give a string: ");
str = refPoint;//same as the comment above.
free(str);
scanf("%s",str);
if (*str == 'Q' && *(str+1) == 'U' && *(str+2) == 'I' && *(str+3) == 'T') {
// why won't if (str == 'QUIT') work?
free(str);
printf("Bye!"); //after printing "Bye!", it crashes.
system("pause"); //it also crashes if i terminate with ctrl+c.
exit(EXIT_SUCCESS); //or just closing it with [x].
}
printf("The string becomes: ");
while (*str != '\0') {
putchar(fnChange(*str));
str++;
}
printf("\n");
}
}
Run Code Online (Sandbox Code Playgroud)
free(str);
scanf("%s",str);
Run Code Online (Sandbox Code Playgroud)
大禁忌,你被释放后不允许使用动态分配的内存.最重要的是,你可以在循环中再次释放它.
这样做是未定义的行为.这几乎可以肯定是导致崩溃的原因.
其他几个问题.您可以使用<=而不是<使代码更具可读性,例如:
if ((c >= 'a') && (c <= 'z')) ...
Run Code Online (Sandbox Code Playgroud)
使用魔术数字32几乎总是一个坏主意.如果您使用的是字母连续的编码(例如ASCII),您可以执行以下操作:
c = c - 'A' + 'a';
Run Code Online (Sandbox Code Playgroud)
将大写转换为小写.
你真正应该做的但是,使用toupper()和tolower()(和isupper()和islower()也,检测的情况下),因为字母不能保证是连续的.
表达式str == 'QUIT'不会按照您的想法执行,因为'QUIT'它不是字符串.相反,它是一个多字节字符文字.但是,即使str == "QUIT"不会按照您的想法进行操作,因为在C中比较字符串的正确方法是:
if (strcmp (str, "QUIT") == 0) ...
Run Code Online (Sandbox Code Playgroud)