简体   繁体   English

.txt 文件到字符数组?

[英].txt file to char array?

I have been trying to read a .txt file with the following text :我一直在尝试读取带有以下文本的 .txt 文件:

Debugging is twice as hard as writing the code in the first place.调试的难度是最初编写代码的两倍。 Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.因此,如果您尽可能聪明地编写代码,根据定义,您就不够聪明来调试它。 - Brian W. Kernighan * - 布赖恩 W. Kernighan *

However when I try to send the .txt file to my char array, the whole message except for the word "Debugging" prints out, I'm not sure why.但是,当我尝试将 .txt 文件发送到我的 char 数组时,打印出除“调试”一词之外的整个消息,我不知道为什么。 Here's my code.这是我的代码。 It must be something simple that I can't see, any help would be much appreciated.它一定是我看不到的简单东西,任何帮助将不胜感激。

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

The line线

File >> quote;

reads the first word into your array.将第一个单词读入数组。 Then the next call to File.get copies over the word that you already read.然后对File.get的下一次调用将复制您已阅读的单词。 So the first word is lost.所以第一个字就丢了。

You should remove the above line from your code and it will function correctly.您应该从代码中删除上面的行,它会正常运行。

I'd usually suggest using a std::string instead of a char array to read into, but I can see that ifstream::get does not support it, closest is streambuf .我通常建议使用std::string而不是 char 数组来读入,但我可以看到ifstream::get不支持它,最接近的是streambuf

The other thing to watch is to check that your file opened correctly.要注意的另一件事是检查您的文件是否正确打开。

The following code does that.下面的代码就是这样做的。

#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";
    }    
}

The ifstream object is convertible to bool (or void* in c++03 world) and so can be tested against for truthiness. ifstream对象可转换为bool (或 c++03 世界中的void* ),因此可以测试其真实性。

A simple char by char read method ( not tested)一个简单的 char by char 读取方法(未测试)

include包括

#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