从文本文件抽取随机非空行实现8球程序的技术问询
Fixing Your Magic 8-Ball Program: Skip Empty Lines & Pick Valid Responses
Hey there! Let's get your 8-ball program working perfectly—right now it's got a couple of quirks that can lead to blank outputs or picking empty lines, but we can fix that easily. Here's a step-by-step solution:
First, Let's Spot the Existing Issues
Your current code has a few pitfalls:
- Using
rand() % 50assumes there are 50 lines, but you only have 11 valid responses. Most of the time, this random number will be higher than the actual number of lines, so nothing gets printed. - It doesn't filter out empty lines—if your text file has blank lines (even by accident), the program might count them and pick one, leading to a silent, empty output.
- There's no check to confirm we actually found valid responses before trying to pick one.
Improved Code That Solves These Problems
We'll use a vector to store only non-empty, valid lines, then pick a random entry from that list. This way we never hit empty lines or out-of-bounds indexes:
#include <iostream> #include <fstream> #include <vector> #include <string> #include <cstdlib> #include <ctime> #include <cctype> using namespace std; int main() { vector<string> validResponses; string line; ifstream inputFile("file.txt"); // Seed random number generator once (do this only once at the start!) srand(static_cast<unsigned int>(time(nullptr))); // Read file and collect only non-empty/non-whitespace lines while (getline(inputFile, line)) { // Check if the line has actual content (not just spaces/tabs) bool hasContent = false; for (char c : line) { if (!isspace(static_cast<unsigned char>(c))) { hasContent = true; break; } } if (hasContent) { validResponses.push_back(line); } } // Clean up: close the file inputFile.close(); // Pick and print a random valid response (or handle empty case) if (!validResponses.empty()) { int randomIdx = rand() % validResponses.size(); cout << validResponses[randomIdx] << endl; } else { cout << "Error: No valid responses found in file.txt!" << endl; } return 0; }
Key Improvements Explained
- Store Valid Lines Only: The
vector<string> validResponsesholds every line that has actual content (not just spaces or tabs). This ensures we never work with empty entries. - Safe Random Selection: Using
rand() % validResponses.size()guarantees we pick an index that exists in our list of valid responses—no more missed outputs from out-of-range numbers. - Whitespace Check: We don't just skip lines with length 0; we also skip lines that are only whitespace (like accidental spaces left in the text file).
- Error Handling: If the file is empty, or all lines are blank, the program tells you instead of crashing or doing nothing.
Quick Note on Your Text File
Make sure your file.txt has each response on its own line. It can have blank lines (the code ignores them), but here's how it should look ideally:
Yes, of course! Without a doubt, yes. You can count on it. For sure! Ask me later. I'm not sure. I can't tell you right now. I'll tell you after my nap. No way! I don't think so. Without a doubt, no. The answer is clearly NO.
内容的提问来源于stack exchange,提问作者nwhitt99




