Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.

C++ fstream help


ghost's Avatar
0 0

I've been trying to fix this problem for a couple hours now, and have no idea what to do. I'm trying to read a single string from a text file into an array (has to be in a char array). This is what the code snippet looks like:

char a[20];

ifstream file;
file.open("test.txt");
file>>a;
file.close();

cout << a;
...

the problem is that, the text file has a space in it, and everytime it gets to the space it stops reading leaving me with only the first word. Anyone have any suggestions?


ghost's Avatar
0 0

Why does it have to be a char?


ghost's Avatar
0 0

im using the system() function with whats in the text file. I tried using a string but it told me i needed to use a char constant. I tested an array and it worked fine but it wasnt the array read from the file.


ghost's Avatar
0 0

Did everything else work when you used a string??


ghost's Avatar
0 0

yep everything… would have worked had it compiled like that. I took out the system() line still using the string and everything else worked. I just cant get it to work with the array.


ghost's Avatar
0 0

Okay change a back to a string then in your system command do something like (I'm doing this from memory 'cause I'm not at home so I don't have my codes)

// All your code....
system(a.c_str());
// All the rest of your code...

I think its that… let me know if it works or not.


ghost's Avatar
0 0

ok, that helps a bit. Apparently i was wrong though… for some reason this line of code: file >> a;

only reads untill it gets to a space, but i have fixed my problem with the code you provided. Thanks


ghost's Avatar
0 0

thanks for your guy's help. The code is now finished and in the C++ code bank, enjoy


ghost's Avatar
0 0

Check out my text editor in C that i posted, it also shows how to read from a file 1 character at a time using structs and linked lists and allocating memory…. but its more advanced