C++读取Matrix A与Matrix B文件时输出重叠问题求助
Hey there! Let's tackle that overlapping output issue you're facing, plus fix that weird duplicate last character (like the 99 instead of 9 in your example).
First, let's break down what's causing the problems:
- Overlapping output: Your MatrixA.txt file doesn't end with a newline, and your code doesn't add any separation between the two matrix outputs—so Matrix B's content gets printed right after Matrix A's.
- Duplicate last character: Using
while (!file.eof())is a common pitfall. The loop runs one extra time after the last character is read, which reprints the final character again.
Here's the fixed code with clear explanations:
#include <iostream> #include <fstream> #include <string> // Added for string parameter support using namespace std; // Wrap file reading logic in a function to avoid repetition void printMatrixFromFile(const string& fileName, const string& matrixLabel) { ifstream file(fileName); if (!file) { cout << "Error opening file: " << fileName << "!!!" << endl; return; } char ch; // Fix: Use the read operation itself as the loop condition // This stops as soon as reading fails (no extra loop iteration) while (file >> noskipws >> ch) { cout << ch; } // Add a newline to separate the two matrices cout << endl; file.close(); } int main() { // Print Matrix A first printMatrixFromFile("MatrixA.txt", "Matrix A"); // Print Matrix B with corrected comment (was mistakenly labeled Matrix A before) printMatrixFromFile("MatrixB.txt", "Matrix B"); return 0; }
Key changes made:
- Fixed the loop condition: Replaced
while (!file.eof())withwhile (file >> noskipws >> ch)—this ensures we only process characters that were successfully read, eliminating the duplicate last character. - Added separation between outputs: A
cout << endl;after each matrix's content ensures Matrix B starts on a new line, no more overlapping. - Reduced code redundancy: Wrapped the file reading logic into a reusable function, making the code cleaner and easier to maintain.
- Fixed the comment typo: The second block's comment now correctly references Matrix B instead of Matrix A.
If you want to keep the exact "Matrix X ----- " label in the output (like your example), you can either:
- Keep that label inside your .txt files (just make sure MatrixA.txt ends with a newline), or
- Add the label directly in the function, right before reading the file content:
cout << matrixLabel << " ----- ";
That should resolve both the overlapping and duplicate character issues!
内容的提问来源于stack exchange,提问作者S. Munirah
相关产品推荐
相关产品推荐

