【发布时间】:2014-09-03 09:03:12
【问题描述】:
所以,这是我第一次在这里发帖,我会尽可能具体。 我必须为我的学校制作一个程序,上面写着:
先写一个获取字符并返回的函数:
- 如果是大写字母,则为相同的字符。
- 如果是小写字母,则为大写字母。
- 反斜杠 ('\') 如果是数字。
- 在任何其他情况下为星号 ('*')。
然后,使用您的函数,创建一个程序,获取字符串并在函数更改后重新打印它。它应该一直要求一个新字符串,直到用户输入“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");
}
}
【问题讨论】:
-
str = refPoint????? -
free(str)然后scanf("%s",str)????你到底希望发生什么??? -
一个小问题(您的代码存在真正的问题,请参阅下面 Joachim 的回答),而不是
c > 'a'-1,您真的应该写c >= 'a'。或者,更好的是,只需使用islower()。 -
refPoint = str;?refPoint不是指针! -
“为什么如果 (str == 'QUIT') 不起作用?” - 因为你需要像
strcmp()这样的函数来比较字符串:if( strcmp( str, "QUIT" ) == 0 ) { .. }