2016-04-01 35 views
0

在調用置換函數後接近底部,我的程序應該打印已添加到我的打印城市字符串中的城市名稱,但它的唯一打印輸出空白。Cout將不會打印我的字符串

像這個程序一樣難,我沒有想到我的打印功能給我最討厭的問題。

int main() 
    { 
    string cities; 
    string printCity = ""; 
    string line; 
    char command = 0; 
    unsigned city = 0; 
    while (getline(cin, line)) 
    { 
     sscanf(line.c_str(), "%c %d", &command, &city); 
     if (command != 'c') 
      break; 
     cities.push_back((unsigned char)city); 
     printCity +=(city); 
    } 

    gFirstCity = cities[0]; 

    unsigned to = 0; 
    unsigned from = 0; 
    uint32_t cost = 0; 

    sscanf(line.c_str(), "%c %d %d %d", &command, &to, &from, &cost); 
    graph[to][from]=cost; 
    graph[from][to]=cost; 


    while (getline(cin, line)) 
    { 
     sscanf(line.c_str(), "%c %d %d %d", &command, &to, &from, &cost); 
     graph[to][from]=cost; 
     graph[from][to]=cost; 
    } 


    permute((char*)cities.c_str()+1, 0, cities.length()-1); 
    cout << "Minimum cost for the tour: "; 
    cout << printCity; 

    cout << " is: "<< minTour << endl; 

    return EXIT_SUCCESS; 



} 
+0

那麼該置換功能,打印正確,唯一的問題是打印城市。它應該是一個由大約13個整數組成的字符串,但它沒有顯示任何內容。 – Remixt

+0

請檢查這個問題,以瞭解如何連接'int'和'string's。此外,下次嘗試消除不相關的代碼。 –

回答

4

如果城市編號爲1,2,3,然後printcities將是包含三個字符的值'\0x01' '\0x02''\0x03',一個字符串。這將打印不好。如果你想讓printcities保持「123」,你需要一個stringstream或者std :: to_string()。

0

我同意其他地方所說的:將一個int連接到一個字符串並不是按照您希望的方式工作。相反,顯式轉換citystring第一,使用這樣的事情:

// note: needs <sstream> 
string int2str(int x) { 
    stringstream ss; 
    ss << x; 
    return ss.str(); 
} 

然後修改您的代碼只是一個位:

printCity += int2str(city); 
+2

或者只是使用標準的庫函數:'printCity + = std :: to_string(city);' –