-1

为什么下面的示例代码可以在 Visual Studio 上正常运行。在 Eclipse、NetBean 或 CodeBlock 中代码可以运行但不能显示结果?谢谢大家。例如:输入一个字符串。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)将调用未定义的行为,因为您尚未初始化数组。Poorstrlen将尝试在未初始化的字节混乱中找到 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 回答