簡體   English   中英

Cout不會打印我的字符串

[英]Cout will not print my string

調用置換后,我的程序應該在靠近底部的位置打印已經添加到我的打印城市字符串中的城市名稱,但是它只能打印出空白。

盡管這個程序很難,但我沒想到我的打印功能會給我帶來最煩人的問題。

    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;



}

如果您的城市編號為1、2、3,則printcities將是包含三個字符的字符串,值分別為'\\0x01' '\\0x02''\\0x03' 這不會很好地打印。 如果您試圖使打印城市保持“ 123”,則需要一個stringstream或std :: to_string()。

我同意其他地方所說的:將int修飾為字符串不能按您希望的方式工作。 相反,首先使用類似以下內容的方式將city顯式轉換為string

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

然后稍微修改一下代碼:

printCity += int2str(city);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM