2012-07-25 52 views
-1

爲什麼下面的示例代碼可以在Visual Studio上正常運行。在Eclipse,NetBean或CodeBlock中,代碼可以運行但不能顯示結果?謝謝大家。例如:輸入一個字符串。 a /大寫的第一個字母。 b刪除字符串內的空格。代碼可以運行,但不會在Eclipse中顯示結果。

#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; 
    } 
+5

這就是你到了那裏的一些可怕的代碼。我建議你儘快掌握一本[良好的C++書](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)。 – 2012-07-25 18:51:49

回答

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 

一般情況下,請你幫個忙,並與std::string取代char*。另外,get a good C++ book

這裏就是你們的榜樣會是什麼樣子在實際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'; 
} 
相關問題