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()aftercin>>n: When you usecin>>n, it reads the integer but leaves the newline character (\n) in the input buffer. The nextgetline()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
cinandgetline()without clearing the buffer, the firstgetline()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:
- Buffer Clearing: After
cin>>n,cin.ignore(...)clears all characters up to and including the newline, so the nextgetline()reads the actual hometown string instead of an empty line. - Multi-Word Support: Using
getline()for all input allows cities with spaces (like "New York" or "San Francisco"). - Structured Route Storage: The
Routestruct stores both endpoints of each route, plus ausedflag to avoid reusing the same route twice. - 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).
- 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
相关产品推荐
相关产品推荐

