C++文件读取无输出问题求助:Code::Blocks 20.03代码调试
Hey there! Let's break down why your code stops outputting after that line, and fix it step by step.
The Core Problems
Your code has two key issues that are causing the missing output:
Wrong Loop Structure for File Reading
Your current read loop checks if the stream is valid before attempting to read a character:while(file){ file.get(ch); cout<<ch; }Here's the problem: when
file.get(ch)hits the end of the file (or fails for another reason), it sets the stream to a failed state—but the loop already passed the check. This means you'll try to printcheven after the read failed, and the loop won't exit cleanly.The fix is to check the result of the
get()call directly, since it returns the stream object (which evaluates tofalseif the read fails):while(file.get(ch)) { cout << ch; }Unchecked File Opening & Missing Creation Flag
When usingios::in|ios::outto open a file, if the file doesn't already exist in your program's working directory, theopen()call will fail silently. Since you don't check if the file opened successfully, all your write operations do nothing, and reading from a failed stream gives no output.To fix this, either:
- Add a check for successful file opening to catch errors early:
file.open("TEXT", ios::in|ios::out); if (!file) { cerr << "Error: Could not open or create the file!" << endl; return 1; } - Add
ios::truncto create the file if it doesn't exist (this will overwrite existing content in the file, which makes sense for your use case):file.open("TEXT", ios::in|ios::out|ios::trunc);
- Add a check for successful file opening to catch errors early:
Bonus: Handling Spaces in Input
A small side note: using cin >> String will only read characters up to the first space. If you want to allow users to input strings with spaces, use cin.getline(String, 80) instead.
Full Corrected Code
Here's your code with all the fixes applied:
#include <iostream> #include <fstream> #include <cstring> #include <stdlib.h> using namespace std; int main() { char String[80]; cout << "Enter a string: "; cin.getline(String, 80); // Allows spaces in input int len = strlen(String); fstream file; cout << "Opening the 'TEXT' file and storing the string in it.\n\n"; file.open("TEXT", ios::in|ios::out|ios::trunc); if (!file) { cerr << "Error: Failed to open file!" << endl; return 1; } for(int i = 0; i < len; i++) file.put(String[i]); file.seekg(0); // Move read pointer to start of file char ch; cout << "\nReading the file contents: "; while(file.get(ch)) { cout << ch; } file.close(); return 0; }
How to Verify
Make sure your program's working directory is where you expect the TEXT file to be (in Code::Blocks, this is usually the folder containing your project's executable). Run the corrected code, input a string, and you should see the file contents printed out as expected.
内容的提问来源于stack exchange,提问作者Arju Aman

