C++如何读取文件忽略空格并提取固定格式行的指定字段
Hey there! Let's tackle your problem step by step—first extracting the exact values you need from each line, then covering how to handle whitespace when reading files in C++.
Since your lines follow a strict, predictable format: ID: HH-123AB, brand: Mercedes-Benz, 128000 miles, 12 L, we can leverage C++'s formatted input to skip the fixed parts and directly capture the data we care about.
Here's a straightforward example that reads each line and extracts the ID, brand, mileage, and fuel consumption:
#include <iostream> #include <fstream> #include <string> #include <limits> // For ignore() if handling spaced brands int main() { std::ifstream input_file("your_input_file.txt"); if (!input_file.is_open()) { std::cerr << "Oops! Couldn't open the input file." << std::endl; return 1; } std::string id, brand; int miles; int liters; // Use double if you expect decimal values like 12.5 // Formatted input skips fixed tokens automatically while (input_file >> std::ws >> "ID:" >> id >> ", brand:" >> brand >> miles >> "miles," >> liters >> "L") { // Do something with your extracted values std::cout << "Extracted: " << id << ", " << brand << ", " << miles << ", " << liters << "\n"; } input_file.close(); return 0; }
Quick note for spaced brand names:
The code above works perfectly if brands don't have spaces (like Mercedes-Benz). If you have brands with spaces (e.g., BMW X5), adjust the brand-reading logic to capture everything up to the next comma:
// Replace the brand reading part with this std::string dummy; input_file >> std::ws >> "ID:" >> id >> ", brand:"; std::getline(input_file >> std::ws, brand, ','); // Read until comma input_file >> miles >> "miles," >> liters >> "L";
C++ offers several straightforward methods to handle whitespace during file reading:
- Default
>>behavior: The>>operator forstd::istreamautomatically skips all leading whitespace (spaces, tabs, newlines) before reading a value. This is why we can seamlessly read integers and strings without worrying about spaces between tokens. std::wsmanipulator: Use this to explicitly skip whitespace, especially before usingstd::getline(which doesn't skip leading whitespace by default). Example:std::string line; std::getline(input_file >> std::ws, line); // Skips leading whitespace before reading the full lineignore()for targeted skipping: If you need to clear leftover characters (like a newline after using>>), useignore()to skip until a specific character:// Ignore all characters up to and including the next newline input_file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
That's all! This approach should reliably extract your desired values while handling whitespace correctly.
内容的提问来源于stack exchange,提问作者Miklos Gergely

