提问者:小点点

字符的输入/输出操作


我正在学习用C++处理文件。 我在code::Blocks20.03中实现的代码与书中的一个程序中给出的代码完全相同,但它在第26行后没有显示输出,即。

cout<<"\nReading the file contents: ";

我想这些台词可能是侠义的,但我无法调试:

while(file){
        file.get(ch);
        cout<<ch;
    }

下面是完整的代码:

#include <iostream>
#include <fstream>
#include <cstring>
#include <stdlib.h>
using namespace std;

int main()
{
    char String[80];

    cout<<"Enter a string: ";
    cin>>String;

    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);

    for(int i=0;i<len;i++)
        file.put(String[i]);

    file.seekg(0);
    char ch;
    cout<<"\nReading the file contents: ";
    while(file){
        file.get(ch);
        cout<<ch;
    }
    file.close();
    return 0;
}

共3个答案

匿名用户

openmode

ios::in | ios::out

如果“text”不存在,则不会创建新文件,但会导致错误。 很可能这个文件不存在,因此您会得到一个错误,并且对流的任何后续输入和输出操作都将被忽略。 你可以用

ios::in | ios::out | ios::trunc

若要销毁现有文件的内容,或在该文件不存在时创建一个新文件,请执行以下操作。

有关更多信息,请参阅https://en.cppreference.com/w/cpp/io/basic_filebuf/open上的表格,其中详细介绍了openmode的所有不同组合。

最后,最好检查文件是否已打开:

if(!file) { /* error */ }

匿名用户

您可以使用is_open()检查文件是否被成功打开,然后使用if else循环来验证文件是否找不到。 您不需要使用iOS::iniOS::out。

下面是一个应该有效的例子:

#include <iostream>
#include <fstream>
using namespace std;

int main () {

  fstream filestr;
  filestr.open ("test.txt");
  if (filestr.is_open())
  {
    filestr << "File successfully open";
    filestr.close();
  }
  else
  {
    cout << "Error opening file";
  }
  return 0;
}

匿名用户

您需要检查循环中的文件结尾。

while(file) {
        file.get(ch);
         if(ch == -1) break;
        cout << ch;
    }

另外,尝试先在写入模式下打开文件,然后关闭它并在读取模式下打开它。

 cout << "Opening the 'TEXT' file and storing the string in it.\n\n";
 ofstream outfile("TEXT");
 if(outfile.is_open()) {
    for(int i = 0; i < len; i++)
        outfile.put(String[i]);

        outfile.close();
}
 ifstream infile("TEXT");
 char ch;
 if(infile.is_open()) {
   cout << "\nReading the file contents: ";
   while(infile) {
            file.get(ch);
            if(ch == -1) break;
            cout << ch;
    }
        infile.close();
   }