含空格字符串读取异常:C++/Java首府问答程序Bug排查
Absolutely, the space in capital names is exactly the root cause here—let’s break down what’s happening, why your code behaves this way, and how to fix it.
First, let’s confirm the weird behavior you’re seeing, which matches your output:
What is the capital of Arkansas?Little Rock The correct answer should be Little Rock What is the capital of California?The correct answer should be Sacramento What is the capital of Colorado?
What’s Wrong With Your Code?
In your C++ code, you’re using cin >> capital to read the user’s input. The problem is that the extraction operator (>>) for cin stops reading as soon as it encounters any whitespace (spaces, tabs, newlines).
Here’s the play-by-play when you input Little Rock for Arkansas:
cinreads only the first word,"Little", into thecapitalvariable.- The second word,
"Rock", plus the newline you pressed, stays stuck in the input buffer. - When the loop moves to the next state (California),
cindoesn’t wait for you to type anything—it just grabs the leftover"Rock"from the buffer. Since"Rock"doesn’t match"Sacramento", it immediately prints the correct answer, and then the next loop iteration starts with an empty buffer, waiting for input.
The exact same issue occurs in Java if you’re using Scanner.next() instead of Scanner.nextLine()—both cin >> and Scanner.next() are designed to read single whitespace-separated tokens, not full lines.
Also, a quick side note: your original code never increments correctCount, so it will always output 0 at the end, even if you got every answer right!
How to Fix the C++ Code
To read entire lines of input (including spaces), use getline(cin, capital) instead. But there’s a gotcha: after any previous use of cin >> (even though you don’t have that here, the newline from pressing enter after input stays in the buffer), getline will read that leftover newline as an empty line. We need to clear that first with cin.ignore().
Here’s the corrected, working version of your code:
#include <iostream> #include <string> #include <limits> // Needed for numeric_limits using namespace std; int main() { string stateCapital[50][2] = { // Fixed array size to [50][2] (only 2 elements per pair) {"Alabama" , "Montgomery"}, {"Alaska" , "Juneau"}, {"Arizona" , "Phoenix"}, {"Arkansas" , "Little Rock"}, {"California" , "Sacramento"}, {"Colorado" , "Denver"}, {"Connecticut" , "Hartford"}, {"Delaware" , "Dover"}, {"Florida" , "Tallahassee"}, {"Georgia" , "Atlanta"}, {"Hawaii" , "Honolulu"}, {"Idaho" , "Boise"}, {"Illinois" , "Springfield"}, {"Indiana" , "Indianapolis"}, {"Iowa" , "Des Moines"}, {"Kansas" , "Topeka"}, {"Kentucky" , "Frankfort"}, {"Louisiana" , "Baton Rouge"}, {"Maryland" , "Annapolis"}, {"Massachusetts" , "Boston"}, {"Michigan" , "Lansing"}, {"Minnesota" , "Saint Paul"}, {"Mississippi" , "Jackson"}, {"Missouri" , "Jefferson City"}, {"Montana" , "Helena"}, {"Nebraska" , "Lincoln"}, {"Nevada" , "Carson City"}, {"New Hampshire", "Concord"}, {"New Jersey" , "Trenton"}, {"New Mexico" , "Santa Fe"}, {"New York" , "Albany"}, {"North Carolina" , "Raleigh"}, {"North Dakota" , "Bismarck"}, {"Ohio" , "Columbus"}, {"Oklahoma" , "Oklahoma City"}, {"Oregon" , "Salem"}, {"Pennsylvania" , "Harrisburg"}, {"Rhode Island" , "Providence"}, {"South Carolina" , "Columbia"}, {"South Dakota" , "Pierre"}, {"Tennessee" , "Nashville"}, {"Texas" , "Austin"}, {"Utah" , "Salt Lake City"}, {"Vermont" , "Montpelier"}, {"Virginia" , "Richmond"}, {"Washington" , "Olympia"}, {"West Virginia" , "Charleston"}, {"Wisconsin" , "Madison"}, {"Wyoming" , "Cheyenne"} }; int correctCount = 0; string capital; for (int i = 0; i < 50; i++){ cout << "What is the capital of " << stateCapital[i][0] << "?" << flush; // Clear all characters up to and including the newline from the buffer cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Read the entire line of input, including spaces getline(cin, capital); if (capital == stateCapital[i][1]){ cout << "Your answer is correct" << endl; correctCount++; // Now increments when answers are right } else { cout << "The correct answer should be " << stateCapital[i][1] << endl; } } cout << "The correct count is " << correctCount << endl; return 0; }
Java Equivalent Fix
For your Java program, swap Scanner.next() with Scanner.nextLine() to read full lines. If you had any prior calls to nextInt() or next(), you’ll need to call scanner.nextLine() once first to consume the leftover newline in the buffer.
Here’s a snippet of the corrected Java loop:
import java.util.Scanner; public class StateCapitalQuiz { public static void main(String[] args) { String[][] stateCapital = { /* Your state-capital pairs here */ }; Scanner scanner = new Scanner(System.in); int correctCount = 0; for (int i = 0; i < stateCapital.length; i++) { System.out.print("What is the capital of " + stateCapital[i][0] + "? "); String capital = scanner.nextLine(); if (capital.equals(stateCapital[i][1])) { System.out.println("Your answer is correct"); correctCount++; } else { System.out.println("The correct answer should be " + stateCapital[i][1]); } } System.out.println("The correct count is " + correctCount); scanner.close(); } }
内容的提问来源于stack exchange,提问作者Neil Shah

