我正在尝试弄清楚如何使用指针使用toupper和tolower。我以为我在正确的道路上。我设法使大写字母正确的指针正确,但由于某种原因,它对小写不起作用。任何建议都会有所帮助。
#include <stdio.h>
#include <ctype.h>
void safer_gets (char array[], int max_chars);
main()
{
/* Declare variables */
/* ----------------- */
char text[51];
char *s1_ptr = text;
int i;
/* Prompt user for line of text */
/* ---------------------------- */
printf ("nEnter a line of text (up to 50 characters):n");
safer_gets(text ,50);
/* Convert and output the text in uppercase characters. */
/* ---------------------------------------------------- */
printf ("nThe line of text in uppercase is:n");
while (*s1_ptr != ' ')
{
*s1_ptr = toupper(*s1_ptr);
putchar(toupper(*s1_ptr++));
}
/* Convert and output the text in lowercase characters. */
/* ---------------------------------------------------- */
printf ("nnThe line of text in lowercase is:n");
while (*s1_ptr != ' ')
{
*s1_ptr = tolower(*s1_ptr);
putchar(tolower(*s1_ptr++));
}
/* Add carriage return and pause output */
/* ------------------------------------ */
printf("n");
getchar();
} /* end main */
/* Function safer_gets */
/* ------------------- */
void safer_gets (char array[], int max_chars)
{
/* Declare variables. */
/* ------------------ */
int i;
for (i = 0; i < max_chars; i++)
{
array[i] = getchar();
/* If "this" character is the carriage return, exit loop */
/* ----------------------------------------------------- */
if (array[i] == 'n')
break;
} /* end for */
if (i == max_chars )
if (array[i] != 'n')
while (getchar() != 'n');
array[i] = ' ';
} /* end safer_gets */
那是因为它永远不会进入第二个循环,因为您修改了指针。在第二个循环重置您的指针到S1_ptr =文本之前,它将起作用。