You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中使用getline()处理多词城市路线拼接的问题

Fixing Multi-Word City Route Concatenation in C++

Hey there! Let's tackle your problem with handling multi-word cities and those annoying getline() input glitches. First, let's break down why those exceptions happen, then fix the code step by step.

Why the Input Glitches Occur

  • Empty getline() after cin>>n: When you use cin>>n, it reads the integer but leaves the newline character (\n) in the input buffer. The next getline() call reads this leftover newline as an empty string instead of the actual city name.
  • Only N-1 routes read: Same buffer issue—if you mix cin and getline() without clearing the buffer, the first getline() in the loop grabs that leftover newline, so you end up with one fewer valid route input.

Solution: Proper Input Handling with getline()

To handle multi-word cities, we need to use getline() for all input, and make sure to clear the input buffer after using cin to read the integer. Here's the revised code, plus explanations of key changes:

#include <iostream>
#include <string>
#include <vector>
#include <limits>

using namespace std;

struct Route {
    string start;
    string end;
    bool used = false;
};

int main() {
    int n;
    string hometown;
    
    // Read city count, then clear the newline from buffer
    cin >> n;
    cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Ignore all characters until newline
    
    // Read hometown (supports multi-word like "New York")
    getline(cin, hometown);
    
    // Read N routes (each in format "CityA-CityB", e.g., "New York-Paris")
    vector<Route> routes(n);
    for (int i = 0; i < n; ++i) {
        string line;
        getline(cin, line);
        
        // Split the line at the '-' to get start and end cities
        size_t dashPos = line.find('-');
        routes[i].start = line.substr(0, dashPos);
        // Trim any leading space after the dash for cleaner input
        routes[i].end = line.substr(dashPos + 1);
        if (!routes[i].end.empty() && routes[i].end[0] == ' ') {
            routes[i].end = routes[i].end.substr(1);
        }
    }
    
    // Build the circular route
    string currentCity = hometown;
    cout << currentCity;
    
    for (int j = 0; j < n; ++j) {
        for (int i = 0; i < n; ++i) {
            if (!routes[i].used) {
                // Check if current city matches start or end of the route (routes are bidirectional)
                if (routes[i].start == currentCity) {
                    currentCity = routes[i].end;
                    cout << "-" << currentCity;
                    routes[i].used = true;
                    break;
                } else if (routes[i].end == currentCity) {
                    currentCity = routes[i].start;
                    cout << "-" << currentCity;
                    routes[i].used = true;
                    break;
                }
            }
        }
    }
    
    cout << endl;
    return 0;
}

Key Improvements:

  1. Buffer Clearing: After cin>>n, cin.ignore(...) clears all characters up to and including the newline, so the next getline() reads the actual hometown string instead of an empty line.
  2. Multi-Word Support: Using getline() for all input allows cities with spaces (like "New York" or "San Francisco").
  3. Structured Route Storage: The Route struct stores both endpoints of each route, plus a used flag to avoid reusing the same route twice.
  4. Bidirectional Route Handling: The code checks both ends of each route, since travel routes work both ways (you can go from A to B or B to A).
  5. Clean Input Splitting: Splits each route line at the - character, and trims any leading space after the dash for more flexible input formatting (e.g., "New York - Paris" works just as well as "New York-Paris").

Example Input:

4
New York
New York-Los Angeles
Los Angeles-Chicago
Chicago-Miami
Miami-New York

Example Output:

New York-Los Angeles-Chicago-Miami-New York

内容的提问来源于stack exchange,提问作者Slavisa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 11:39:04