- 程序目的:我编写了一个字符串输入的函数,函数中采用指针表示每个字符的处理位置;
- 问题描述:无法将输入的字符成功转化为小写;
- 所做的尝试: 3.1 进一步尝试发现st并不是一个字符串,而且strlen(st)返回值是0。 3.2 如果用数组表示法,则可以正常运行且能够将输入的字符转换成小写字符。
- 代码如下:
#include
#include
#include
#define ANSWER "Grant"
#define SIZE 40
char *s_gets(char * st, int n);
int main (void)
{
char try1[SIZE];
char answer[] = ANSWER;
int i = 0;
while(answer[i])
{
answer[i] = tolower(answer[i]);
i++;
}
puts("Who is buried in Grant's tomb?");
s_gets(try1, SIZE);
while(strcmp(try1, answer) !=0)
{
puts("No, that's wrong. Try again.");
s_gets(try1, SIZE);
}
puts("That's Right!");
return 0;
}
char * s_gets(char * st, int n)
{
char * ret_val;
char * pc;
int j = 0;
ret_val = fgets(st, n, stdin);
if(ret_val)
{
while((*st) != '\n' && (*st) != '\0')
{
st++;
}
if ((*st) == '\n')
{
(*st) = '\0';
}
else
while(getchar() != '\n')
continue;
}
while(st[j])
{
st[j] = tolower(st[j]);
j++;
}
return ret_val;
}
以下程序可以正常运行
char * ret_val;
int i = 0, j = 0;
ret_val = fgets(st, n, stdin);
if(ret_val)
{
while(st[i] != '\n' && st[i] != '\0')
i++;
if (st[i] == '\n')
st[i] = '\0';
else
while(getchar() != '\n')
continue;
}
while(st[j])
{
st[j] = tolower(st[j]);
j++;
}
return ret_val;
}*/