2014-03-01 47 views
2

我有此代碼段,目的是獲取系統PATH變量中的路徑列表並將它們打印在CMD控制檯上;打印到控制檯時在字符之間出現額外符號

#include <iostream> 
#include <string> 
#include <list> 
#include <cstdlib> 
using namespace std; 

int main() 
{ 
    string path = getenv("PATH"); 

    string tempo = ""; 
    list<string> pathList; 

    for(size_t n = 0; n < path.size(); n++) 
    { 
     char delimiter = ';'; 

     if(path.at(n) == delimiter) 
     { 
      if(!tempo.empty()) 
      { 
       pathList.push_back(tempo); 
      } 
      tempo.clear(); 
     } 
     else{ 
      char aChar = path.at(n); 
      tempo.append(&aChar); 
     } 
    } 

    list<string>::iterator listIter; 

    for(listIter = pathList.begin(); listIter != pathList.end(); listIter++) 
    { 
     cout << *listIter << endl; 
    } 

    return 0; 
} 

我每次編譯和CMD控制檯我得到類似這樣的輸出線路上運行;

C►■":►■"\►■"P►■"y►■"t►■"h►■"o►■"n►■"2►■"6►■"\►■"S►■"c►■"r►■"i►■"p►■"t►■"s►■" 

難道是內存損壞嗎?我究竟發現了什麼? 上午在Windows 7 64位,編譯使用MinGW的(G ++ 4.8)]

+0

這是* waaaaay *太漂亮是 「腐敗」! – user2864740

回答

3

再仔細看看下面的兩個語句:

char aChar = path.at(n); 
tempo.append(&aChar); 

顯然,你想一個char追加到std::string。但是,您實際上會追加一個NUL終止字符串到tempo

與替換代碼:

char aChar = path.at(n); 
tempo += aChar; 

或:

char aChar = path.at(n); 
tempo.push_back(aChar); 
+0

謝謝,這兩個選項的作品。 – Amani

+0

只是一個挑剔。他試圖追加的字符串(或者說char *)不是以null結尾的。 –

相關問題