简体   繁体   English

Cout不会打印我的字符串

[英]Cout will not print my string

Near the bottom after calling permute my program is supposed to print the city names that have been added to my print city string, but its only printing out blanks. 调用置换后,我的程序应该在靠近底部的位置打印已经添加到我的打印城市字符串中的城市名称,但是它只能打印出空白。

as hard as this program was to make I didn't expect my print function to give me the most annoying issue. 尽管这个程序很难,但我没想到我的打印功能会给我带来最烦人的问题。

    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;



}

If your cities are numbered 1, 2, 3, then printcities will be a string containing three characters, of value '\\0x01' '\\0x02' and '\\0x03' . 如果您的城市编号为1、2、3,则printcities将是包含三个字符的字符串,值分别为'\\0x01' '\\0x02''\\0x03' This won't print well. 这不会很好地打印。 If you were trying to get printcities to hold "123", you either need a stringstream, or std::to_string(). 如果您试图使打印城市保持“ 123”,则需要一个stringstream或std :: to_string()。

i agree with what has been said elsewhere: concatting an int to a string isn't working the way you want it to. 我同意其他地方所说的:将int修饰为字符串不能按您希望的方式工作。 instead, explicitly convert city into a string first, using something like this: 相反,首先使用类似以下内容的方式将city显式转换为string

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

then modify your code just a bit: 然后稍微修改一下代码:

printCity += int2str(city);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM