简体   繁体   中英

.txt file to char array?

I have been trying to read a .txt file with the following text :

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 *

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. 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. 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 .

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.

A simple char by char read method ( not tested)

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();
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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