-4

main.cpp

#include <iostream>
#include "Module2.h"

int main()
{
std::cout<<"This is a test of Module2.h"<<std::endl;
std::cout<<UCase("This is a test of UCase")<<std::endl;
std::cout<<LCase("This is a test of LCase")<<std::endl;
system("pause");
return 0;

}

Module2.h

#include <iostream>
#include "Module2.h"

int main()
{
std::cout<<"This is a test of Module2.h"<<std::endl;
std::cout<<UCase("This is a test of UCase")<<std::endl;
std::cout<<LCase("This is a test of LCase")<<std::endl;
system("pause");
return 0;

}

Module2.cpp

///////////////////////////////////////////////////
//Module : Module2.cpp
//
//Purpose : Shows the usage of modular functions
///////////////////////////////////////////////////

#include "Module2.h"

///////////////////////////////////////////////////
//UCase()

char *UCase(char *str)
{
//convert each char in  the string to uppercase
//
int len = strlen(str);
for ( int i ; i < len ; i++)
{
    std::cout<<"In UCase"<<std::endl;
     str[i]=toupper(str[i]);
}

return str;
}

///////////////////////////////////////////////////
//LCase()

char *LCase(char *str)
{
//convert each char in  the string to uppercase
//
int len = strlen(str);
for ( int i ; i < len ; i++)
{
    std::cout<<"In LCase"<<std::endl;
    str[i]=tolower(str[i]);
}  
return str;
}

実行すると、警告もエラーもありません。ただし、弦の上下はしません。for ループが間違っていると思っていましたが、正しいようです。私のコードの何が問題なのですか。

4

3 に答える 3

2

主な問題は、 などの文字列リテラルを変更しようとしていることです"This is a test of UCase"。これは未定義の動作です。charリテラルを変更可能な配列にコピーする必要があります。

char*また、正当な理由により、文字列リテラルへのバインドは推奨されておらず、禁止されていることにも注意してください。これにより、警告が発生するはずです。

UCase("This is a test of UCase") // not good: binding char* to literal

コードには他にも問題があります。初期化されていない変数を含むループでの未定義の動作(UB)、

for ( int i ; i < len ; i++) // using uninitialized i: UB

ドキュメントも参照する必要がtoupperありtolowerます。intどちらも、値にいくつかの制限を付けて受け入れます。未定義の動作を引き起こす値を渡さないようにする必要がありますが、署名charできることに注意してください。たとえば、呼び出す前に unsigned char にキャストする必要がありtoupperますか?を参照してください。

于 2015-01-26T23:02:39.580 に答える
1

このようなループには、未定義の動作があります。

for ( int i ; i < len ; i++)

iその理由は、 value で開始しなかったためです0
値がどこから始まるかわかりませんi!
かもしれない-10、かもしれない824

値を初期化したい場合、初期化する必要があります。
私は提案します:

for (int i=0; i < len; i++)
于 2015-01-26T23:06:44.830 に答える
0
char *UCase( char *str)
{
char ch;
int i=0;

while(str[i])
{
    ch=str[i];
    putchar(toupper(ch));
//putchar : The value is internally converted to an unsigned char when written.
    i++;
}
}

///////////////////////////////////////////////////
//LCase()

char *LCase(char *str)
{
char ch;
int i=0;

while(str[i])
{
    ch=str[i];
    putchar(tolower(ch));
    i++;
}
}

最後にこれを書きます。とはいえ、まだよくわかりませんが、学びました

#include <ctype.h>
int tolower( int ch );

tolower toupper は毎回 1 文字しか変更できないため、変更できません。

tolower ("This is a test of LCase");

このようなコード。

于 2015-01-27T02:48:24.937 に答える