-1

以下のサンプル コードが Visual Studio で正常に動作する理由。Eclipse、NetBean、または CodeBlock では、コードを実行できますが、結果を表示できませんか? 皆さんありがとう。例: 1 つの文字列を入力します。a/ 大文字の最初の文字。b/ 文字列内のスペースを削除します。

#include "iostream"
    #include "string.h"
    using namespace std;

    #define MAX 255

    //uppercase first letter
    char* Upper(char* input)
    {
        char* output = new char[MAX];

        bool isSpace = false;
        for (int i = 0; i < strlen(input); i++)
        {
            output[i] = input[i];
            if (isSpace)
            {
                output[i] = toupper(output[i]);
                isSpace = false;
            }
            if (output[i] == ' ') isSpace = true;
        }
        output[strlen(input)] = '\0'; // end of the string
        output[0] = toupper(output[0]); // first character to upper

        return output;
    }
    //remove space inside the string
    char* RemoveSpaceInside(char* input)
    {
        char* output = new char[MAX];
        strcpy(output, input);

        int countWhiteSpace = 0;
        for (int i = 0; i < strlen(output); i++)
        {
            if (output[i] == ' ')
            {
                for (int j = i; j < strlen(output) - 1; j++) // move before
                {
                    output[j] = output[j + 1];
                }
                countWhiteSpace++;
            }
        }
        output[strlen(output) - countWhiteSpace] = '\0'; // end of the string

        return output;
    }

    int main()
    {
        char* name = new char[MAX];
        cout << "Enter name: "; cin.getline(name, strlen(name)); 
        cout << "Your name: " << name << endl;

        cout << "\n******* Q.A *******\n";
        char* qa  = Format2VN(name);
        cout <<  qa << endl;

        cout << "\n******* Q.B *******\n";
        char* qb = RemoveSpaceInside(name);
        cout << qb << endl;
        return 0;
    }
4

1 に答える 1

2
char* name = new char[MAX];
cout << "Enter name: ";
cin.getline(name, strlen(name));

strlen(name)配列を初期化していないため、呼び出すと未定義の動作が呼び出されます。貧弱なstrlen人は、初期化されていないバイトの混乱で NUL 文字を見つけようとします。間違いなく良い考えではありません。

おそらくあなたが望むのは:

cin.getline(name, MAX);   // not sure if MAX or MAX-1 or whatever

一般に、自分に有利に働き、 に置き換えchar*ますstd::string。また、優れた C++ の本を入手してください。

実際の C++ での例は次のようになります。

#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>

std::string upper_first_letter(std::string s)
{
    if (!s.empty()) s[0] = toupper(s[0]);
    return s;
}

std::string remove_spaces(std::string s)
{
    s.erase(std::remove_if(s.begin(), s.end(), isspace), s.end());
    return s;
}

int main()
{
    std::string name;
    std::cout << "Enter name: ";
    std::getline(std::cin, name);

    std::cout << name << '\n';
    std::cout << upper_first_letter(name) << '\n';
    std::cout << remove_spaces(name) << '\n';
}
于 2012-07-25T18:49:49.050 に答える