繁体   English   中英

.txt 文件到字符数组?

[英].txt file to char array?

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

调试的难度是最初编写代码的两倍。 因此,如果您尽可能聪明地编写代码,根据定义,您就不够聪明来调试它。 - 布赖恩 W. Kernighan *

但是,当我尝试将 .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 >> 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* ),因此可以测试其真实性。

一个简单的 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();
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM