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

含空格字符串读取异常:C++/Java首府问答程序Bug排查

Why does my state capital quiz fail on multi-word capitals (like "Little Rock")?

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:

  1. cin reads only the first word, "Little", into the capital variable.
  2. The second word, "Rock", plus the newline you pressed, stays stuck in the input buffer.
  3. When the loop moves to the next state (California), cin doesn’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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:40:10