-2

输出与输入相同,我在哪里犯了错误?请检查测试版本,它打印 'A' 的 ASCII 码而不是 A 为什么会这样?

循环中的第一个 if 条件是确保字符串仅以有效字符而不是空格开头。

void caps(char* p)
{
   char* begin=NULL;
   char* temp=p;

    while(*temp)
    {

      if((begin == NULL) && (*temp!= ' '))
        begin=temp;

      if(begin && ((*(temp+1) == ' ' ) || (*(temp+1)=='\0')))
      {
         toupper(*temp);
         begin=NULL;
      }

         temp++;
    }

 cout<<p;
}


int main()
{
  char str[]={"i like programming"};
  cout<< str <<endl;
  caps(str);
  return 0;
}

测试

如果我使用 printf("%c",toupper(a)) 它会正确打印 'A'。

#include <iostream>
#include <ctype.h>

using namespace std; 

int main()
{
   char a= 'a';
   cout<<toupper(a); //prints ASCII code of A(65) but why not 'A' ?
   return 0;
}
4

1 回答 1

-3

好吧,在第一个代码中cout << str << endl;str 是一个指针(它的类型是 char*)。要输出 str 的第一个字符,请使用cout << str[0];or cout << *str;。并且 toupper() 返回 int,而不是 char,所以你需要转换结果:

cout << (char)toupper(a);
于 2015-04-22T11:40:51.253 回答