2017-02-18 88 views
-1

嗨,大家好我有以下代碼,我不明白爲什麼在函數「strcount」最後一行不再顯示整個字符串? 在此先感謝!計數字符計數器卡住後?

#include <iostream> 
const int ArSize = 10; 
void strcount(const char * str); 

int main() 
{ 
    using namespace std; 
    char input[ArSize]; 
    char next; 

    cout << "Enter a line:\n"; 
    cin.get(input, ArSize); 
    while(cin) 
    { 
     cin.get(next); 
     while(next != '\n') 
      cin.get(next); 
     strcount(input); 
     cout << "Enter next line (empty line to quit):\n"; 
     cin.get(input, ArSize); 
    } 
    void strcount(const char * str) 
    { 
     using namespace std; 
     static int total = 0; 
     int count = 0; 

     cout << "\"" << str <<"\" contains "; 
     while(*str++) 
      count++; 
     total += count; 
     cout << count << " characters\n"; 
     cout << total << " characters total\n" << endl; 
     cout << str << endl; 
    } 
+1

解決此類問題的正確工具是您的調試器。在*堆棧溢出問題之前,您應該逐行執行您的代碼。如需更多幫助,請閱讀[如何調試小程序(由Eric Lippert撰寫)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您應該\編輯您的問題,以包含一個[最小,完整和可驗證](http://stackoverflow.com/help/mcve)示例,該示例再現了您的問題,以及您在調試器。 –

+0

你爲什麼期望'cout << str'打印原始字符串?你確實意識到你正在修改while循環中的'str'指針,對吧? –

+0

我推薦使用'std :: string'和'std :: getline'來讀取用戶的文本。比擔心數組溢出或丟失nul終止字符容易得多。 –

回答

2

在功能strcount

while(*str++) 

增量str,直到你到達字符串的結尾。

然後試圖輸出

cout << str << endl; 

將顯示任何東西,因爲現在str指向字符串的結尾。

+0

謝謝大家的幫助,現在我明白了。 – AndyE