【问题标题】:.txt file to char array?.txt 文件到字符数组?
【发布时间】:2017-01-30 11:00:16
【问题描述】:

我一直在尝试读取包含以下文本的 .txt 文件:

首先,调试的难度是编写代码的两倍。因此,如果您尽可能巧妙地编写代码,那么根据定义,您还不够聪明,无法对其进行调试。 - 布赖恩·W·克尼汉 *

但是,当我尝试将 .txt 文件发送到我的 char 数组时,除了“调试”这个词之外的整个消息都会打印出来,我不知道为什么。这是我的代码。它必须是一些我看不到的简单的东西,任何帮助将不胜感激。

#include <iostream>
#include <fstream>

using namespace std;

int main(){

char quote[300];

ifstream File;

File.open("lab4data.txt");

File >> quote;


File.get(quote, 300, '*');


cout << quote << endl;
}

【问题讨论】:

  • 这段代码没有意义,即使故意读作伪代码也是如此。您能否尝试改进您的问题,以解释您真正想要实现的目标。
  • 删除 File &gt;&gt; quote; 这是第一个单词被写入数组,然后被File.get 的调用覆盖。
  • 谢谢你,解决了它
  • 最好使用std::string 而不是char[n]

标签: c++ arrays iostream


【解决方案1】:

线

File >> quote;

将第一个单词读入你的数组。然后对File.get 的下一次调用会复制您已经阅读的单词。所以第一个词就丢了。

您应该从您的代码中删除上述行,它会正常运行。

我通常建议使用std::string 而不是char 数组来读取,但我可以看到ifstream::get 不支持它,最接近的是streambuf

要注意的另一件事是检查您的文件是否正确打开。

下面的代码就是这样做的。

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

using namespace std;

int main(){

    char quote[300];
    ifstream file("kernighan.txt");

    if(file)
    {
        file.get(quote, 300, '*');
        cout << quote << '\n';
    } else
    {
        cout << "file could not be opened\n";
    }    
}

ifstream 对象可转换为 bool(或 c++03 世界中的 void*),因此可以进行真实性测试。

【讨论】:

    【解决方案2】:

    一个简单的char by char读取方法(未测试)

    包括

    #include <fstream>
    
    using namespace std;
    
    int main()
    { 
        char quote[300];
        ifstream File;
        File.open("lab4data.txt");
        if(File)
        {
             int i = 0;
             char c;
             while(!File.eof())
             {
                 File.read(&c,sizeof(char));
                 quote[i++] =c;
             }   
             quote[i]='\0';          
             cout << quote << endl;
             File.close();
        }
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多