【问题标题】:get() function in c++ not working for filesc ++中的get()函数不适用于文件
【发布时间】:2017-11-18 04:53:53
【问题描述】:

我在代码块中编写了以下代码,由于我是编程新手,所以我想用简单的话来了解问题。如果 open() 构造函数不存在,它会创建一个新文件吗?

#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;
int main()
{
  char str[80];
  cout<<"Enter a string : ";cin>>str;
  int len=strlen(str);
  fstream file;
  file.open("TEXT",ios::in|ios::out);
  for(int i=0;i<len;i++)
  file.put(str[i]);
  file.seekg(0);
  char ch;
  cout<<"\nPrintitng Contents....\n";
  int k=0;
  while(file)
  {
    file.seekg(k);
    file.get(ch);
    cout<<ch;
    k++;
  }

  return 0;
}

【问题讨论】:

标签: c++ file


【解决方案1】:

我认为您没有“TEXT”。如果您要读取的文件不存在,则 fstream::open 不会生成文件。

所以你可以尝试在不同的流中读写。

以下代码将对您有所帮助。

#include<iostream>
#include<fstream>
#include<cstring>

using namespace std;

int main()
{
    char str[80];
    cout << "Enter a string : "; 
    cin >> str;
    int len = strlen(str);

    ofstream fout;
    fout.open("TEXT.txt");

    for (int i = 0; i<len; i++)
        fout.put(str[i]);

    fout.close();

    ifstream fin;
    fin.open("TEXT.txt");

    char ch;
    cout << "\nPrintitng Contents....\n";

    while (!fin.eof())
    {
        fin.get(ch);
        cout << ch;
        ch = NULL;
    }

    fin.close();

    return 0;
}

你可以像这样改进你的代码

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    string str;

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

    ofstream fout;
    fout.open("TEXT.txt");

    fout << str;

    fout.close();

    str.clear();

    ifstream fin;
    fin.open("TEXT.txt");

    cout << "\nPrintitng Contents....\n";

    fin >> str;
    cout << str;

    fin.close();

    return 0;
}

【讨论】:

  • 几乎完全正确,但您需要阅读Why is iostream::eof inside a loop condition considered wrong? 并快速更正。
  • iostream::eof 在光标到达文件末尾时返回 true,在其他情况下返回 false。所以让循环在“不是”文件结束时继续循环。
  • 第二个是在 C++ 中完全正确的方法,但while (!fin.eof()) 的大问题是它在读取和查找 eof 之前测试 eof。 fin.seekg(k);fin.get(ch); 可能因任何原因失败,包括找到 eof 和 ch 仍在使用,可能会打印垃圾。此外,如果在找到文件末尾之前读取失败,您将陷入无限循环,因为您永远无法到达文件末尾。
  • 我认为提问者的问题只是“无法打开文件”。所以我没有考虑读取循环。在这种情况下 seekg() 不需要。 fstream::get() 自动增加 cursur 指针,所以你可以删除 seekg()。但最后仍然是第一个循环两次打印相同的字符。这是因为字符串末尾有 '\0' 字符。所以你应该在每个循环中清除 ch 。谢谢你解决我的错
【解决方案2】:

我认为下面的代码更适合 C++

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
    string str;
    string newStr;
    cout << "Enter a string : "; cin >> str;
    int len = str.length();
    fstream file;
    file.open("TEXT", ios::out| ios::in );
    if (!file.is_open())
        return 0;
    file << str;
    file.seekg(0,file.beg);
    char ch;
    cout << "\nPrintitng Contents....\n";

    file >> newStr;
    cout << newStr;
    file.close();

    return 0;
}

【讨论】:

  • 重读,更合适,但重复提问者的错误,并没有解决问题
猜你喜欢
  • 1970-01-01
  • 2013-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-27
  • 1970-01-01
相关资源
最近更新 更多