2014-09-03 67 views
-2

我想从用户输入的字符数组中只获取字母字符。这里是一个片段:C++字符数组 - 为什么垃圾?

const int SIZE(100); 

int main() 
{ 
    char* entryTextArray = new char[SIZE]; 
    char* adjustedTextArray= new char[SIZE]; 
    int i, j; 

    cout << "Enter text, and I will tell you if it is a palindrome!" << endl; 
    cin.get(entryTextArray, SIZE); 

    cout << "Length of char array is " << strlen(entryTextArray) << endl; 

    for(i=0, j=0; i <= (strlen(entryTextArray)); i++) { 

     if(isalpha(entryTextArray[i]) && (entryTextArray[i] != '\0')) { 

      adjustedTextArray[j] = entryTextArray[i]; 
      cout << adjustedTextArray[j] << endl; 
      j++; 

     } 
    } 
    cout << adjustedTextArray << endl; 

} 

当我编译时,adjustedTextArray的COUT显示正确的个人entrys,但环外的COUT是进入文本,其次是垃圾。我不知道什么是错的!帮帮我?!

+2

有一个非常好的'std :: string'和'std :: remove_if'你可以使用。 – chris 2014-09-03 23:54:58

+3

'adjustedTextArray'不是NUL终止的。在打印之前,请执行'adjustedTextArray [j] = 0'。 – 2014-09-03 23:55:04

+0

谢谢你! – DanielGagnon 2014-09-03 23:58:05

回答

3

你具备的条件:

if (something && (entryTextArray[i] != '\0')) 

,这样你就明确地避免对NUL结尾值复制从entryTextArrayadjustedTextArray。所以你需要手动放置它。

但是由于您使用std::string在C++中工作,这样做更有意义。