我刚开始学习C。我正在制作下面的程序:
#include<stdio.h>
#include<ctype.h>
int main()
{
char s1[1000];
char s2 [1000];
/* void countchar (const char * const); */
void reverse(const char * const);
char manipulate (char , const char);
printf ("Enter sentence number 1:n");
gets (s1);
printf ("nEnter sentence number 2:n");
gets (s2);
printf ("nThe two sentences entered are:n1. %sn2. %snn", s1, s2);
/* printf ("_______________________________________nn");
countchar (s1, s2); */
printf ("_______________________________________nn"
"The first sentence reversed is:n");
reverse (s1);
printf ("n________________________________________n");
manipulate (s1, s2);
return 0;
}
void reverse (const char * const s1Ptr)
{
if (s1Ptr [0] == ' ')
return;
else /*{
if (isupper (s1Ptr [0]))
tolower (s1Ptr [0]);
else toupper (s1Ptr [0]);
*/
reverse (&s1Ptr[1]);
putchar (toupper (s1Ptr [0]));
}
char manipulate(char s1, const char s2)
{
printf ("10 characters of first sentence + 10 characters of second sentence:n%s", strncat (s1, s2, 10));
}
程序将阅读两句话,然后计算字符数,反转第一句并将所有小写转换为大写,反之亦然,并将第二段中的 10 个字符附加到第一段。
追加字符的操作不起作用。你能帮我解决吗?在函数反转中,反之亦然如何转换大小写?因为我只能从小写到大写
带有/* 的部分是因为我不知道如何制作函数。我真的需要帮助,请指出我的错误并帮助我修复它们。谢谢。
我已经在您发布的代码中添加了评论:
void reverse (const char * const s1Ptr) // don't define as const
{
if (s1Ptr [0] == ' ') // testing agaist 0 will do
return;
else /*{
if (isupper (s1Ptr [0]))
tolower (s1Ptr [0]); // nothing done with the result
else toupper (s1Ptr [0]); // nothing done with the result
*/
reverse (&s1Ptr[1]); // recursion? A simple loop would do
putchar (toupper (s1Ptr [0])); // OP: "Function will only uppercase it"
}
使用更简单的指向字符的方式重写了此代码。您仍然需要反转两个字符串中的一个,但我会留给您弄清楚。
void reverse (char * s1Ptr) // don't define as const
{
if (*s1Ptr == 0) // terminate recursion
return;
else {
if (isupper (*s1Ptr)) // simpler way of writing s1Ptr[0]
*s1Ptr = tolower (*s1Ptr); // put result back in the string
else *s1Ptr = toupper (*s1Ptr); // because you manipulate it later
}
putchar (*s1Ptr); // swapped last two lines round
reverse (s1Ptr+1); // simpler way of pointing to next character
}
"用于附加字符的函数操作不起作用。"是的,它是!