2013-05-12 66 views
0

這有點複雜,但基本上我正在製作一個程序,我的一個功能有點奇怪。該函數被饋送字符數組,第一時間是代碼添加 n和1,我不知道爲什麼

new_sensor_node SN42 42 3.57 5.0 7

現在的功能僅僅打印出每個單獨的「令牌」(每個字符集的由空格隔開)。然後打印一個空格,然後打印令牌中的字符數。但由於某種原因,最後一個標記總是打印出奇怪的,並計算出額外的1個字符。

這裏的功能:

int parseCommandLine(char cline[], char *tklist[]){ 
    int i; 
    int length; 
    int count = 0; //counts number of tokens 
    int toklength = 0; //counts the length of each token 
    length = strlen(cline); 

    for (i=0; i < length; i++) { //go to first character of each token 

     if (((cline[i] != ' ' && cline[i-1]==' ') || i == 0)&& cline[i]!= '"') { 

      while ((cline[i]!=' ')&& (cline[i] != '\0')){ 
       toklength++; 
       cout << cline[i]; 
       i++; 
      } 
     cout << " " << toklength << "\n\n"; 
      cout << "\n"; 
      toklength = 0; 
     count ++; 
     } 
     if (cline[i] == '"') { 
      do { 
       i++; 
      } while (cline[i]!='"'); 
      count++; 
     } 
    } 
    //cout << count << "\n"; 
    return 0; 

而這裏的輸出(對於第一個數組):

new_sensor_node 15 


SN42 4 


42 2 


3.57 4 


5.0 3 


7. 
3 

什麼可能會導致這有什麼想法?我懷疑它可能與我如何處理空字符有關

+0

你知道['strtok'](http://en.cppreference.com/w/c/string/byte/strtok)函數嗎?這可能有幫助。 – 2013-05-12 04:12:22

回答

3

這很可能是輸入字符串實際上在最後包含換行符。根據您讀取輸入的方式,它可能會或可能不在輸入中。例如,fgets函數讀取換行符並將其保留在緩衝區中。

特別是由於您實際上沒有對輸入字符串進行任何實際的標記或修改,所以您只需逐字輸出字符,這是非常可能的情況。

+0

原來每行末尾都有一個\ r,所以我的代碼在它之前沒有停止,因爲它只查找'\ 0'或'\ n'。謝謝! – Acoustic77 2013-05-13 18:33:58

相關問題