.txt文件转换为字符数组

.txt file to char array?

本文关键字:字符 数组 转换 文件 txt      更新时间:2023-10-16

我一直在尝试读取一个.txt文件,其中包含以下文本:

调试的难度是编写代码的两倍。因此,如果您尽可能聪明地编写代码,那么根据定义,您还没有聪明到可以调试它。——Brian W. Kernighan *

然而,当我尝试将。txt文件发送到我的char数组时,除了"Debugging"这个词外,整个消息都打印出来了,我不知道为什么。这是我的代码。一定是什么简单的事情,我看不出来,任何帮助将不胜感激。

#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 >> quote;

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

你应该从你的代码中删除上面的行,它将正常工作。

我通常建议使用std::string而不是字符数组来读取,但我可以看到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 openedn";
    }    
}

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

一个简单的逐字符读取方法(未测试)

<标题>包括
#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]='';          
         cout << quote << endl;
         File.close();
    }

}