isupper(), islower(), toupper(), tolower() 函数在 C++ 中不起作用

the isupper(), islower(), toupper(), tolower() functions not working in c++

本文关键字:C++ 不起作用 toupper islower isupper tolower 函数      更新时间:2023-10-16

我有一个这样的代码片段:

char choice;
do
{
    cout << "A. Option 1" << endl;
    cout << "B. Option 1" << endl;
    cout << "C. Option 1" << endl;
    cout << "D. Option 1" << endl;
    cout << "Option: ";
    cin >> choice;
    if(islower(choice) == 0){ toupper(choice); } // for converting Lower alphabets to Upper alphabets so as to provide flexibility to the user
}while((choice != 'A') && (choice != 'B') && (choice != 'C') && (choice != 'D'));

但它不会将低字母转换为高字母......我不知道为什么。。。我正在使用的操作系统是 Windows 7,编译器是 Visual C++(请注意,我已经在其他编译器中测试了此代码,但同样的问题)......

你应该使用返回值,toupper按值(而不是引用)获取字符并返回大写结果:

choice = toupper(choice);
^^^^^^^^

此外,条件应反转:

if (islower(choice)) // not: if(islower(choice) == 0)

 

使用此代码,toupper本身检查字符是否为小写:

cin >> choice;
choice = toupper(choice);

这行代码

if(islower(choice) == 0){ toupper(choice); }

应该重写如下,

if(islower(choice)){ choice = toupper(choice); }

函数,

int toupper ( int c );

返回值大写等效于 c(如果存在此类值),否则为 c(未更改)。该值作为 int 值返回,该值可以隐式转换为 char。

托上

islowerisupper告诉字符是大写还是小写。

touppertolower不会转换。它接受int参数并返回一个转换字符的int

要转换,请使用以下命令:

  choice = toupper(choice);