使用C++ Vector反转文件字符串时,如何处理单词间的空格?
Hey there! I notice your current code reverses text but drops all spaces—let's fix that right away. The root problem is how you're reading characters from the file:
Why Your Code Skips Spaces
The file >> i operator automatically skips over whitespace characters (spaces, tabs, newlines) when reading input. That means your vector<char> never even stores those spaces in the first place, so they disappear entirely when you reverse the content.
Solution 1: Read Every Character (Including Whitespace)
Instead of using >>, switch to file.get(i)—this method reads every single character from the file, including spaces and newlines. Here's your updated code (plus a missing header you need for std::reverse):
#include<iostream> #include<vector> #include<fstream> #include<algorithm> // Don't forget this for std::reverse! using namespace std; int main(){ ifstream file("file.txt"); char i; vector<char> vec; if(file.fail()){ cerr << "Error opening file!" << endl; exit(1); } // Read every character, including spaces and newlines while(file.get(i)){ vec.push_back(i); } reverse(vec.begin(), vec.end()); // Print the fully reversed content for(char c : vec){ cout << c; } cout << endl; return 0; }
Solution 2: Use std::string (Cleaner, More Readable Approach)
Instead of a vector<char>, using a std::string makes the code more concise. You can even read the entire file content in one go with istreambuf_iterator:
#include<iostream> #include<fstream> #include<algorithm> #include<string> using namespace std; int main(){ ifstream file("file.txt"); if(!file.is_open()){ cerr << "Error opening file!" << endl; return 1; } // Read the entire file into a string (preserves all characters) string content((istreambuf_iterator<char>(file)), istreambuf_iterator<char>()); reverse(content.begin(), content.end()); cout << content << endl; return 0; }
Key Takeaway
The >> operator is perfect for reading words or numbers, but if you need to preserve every character (including whitespace), use get() for single characters or read the entire file content at once with a string.
内容的提问来源于stack exchange,提问作者user9693913

