Cout不会打印我的字符串

Cout will not print my string

本文关键字:我的 字符串 打印 Cout      更新时间:2023-10-16

在调用permute后,我的程序应该打印添加到我的打印城市字符串中的城市名称,但它只打印空白。

尽管这个程序很难制作,但我没想到我的打印功能会给我带来最烦人的问题。

    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将是一个包含三个字符的字符串,值为'x01' 'x02''x03'。这印刷不好。如果您试图让printcities保持"123",则需要一个字符串流或std::to_string()。

我同意其他地方所说的:将int插入字符串并不是你想要的方式。相反,首先显式地将city转换为string,使用如下内容:

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

然后稍微修改一下你的代码:

printCity += int2str(city);