Hi guys I'm new here and a little new in c/c++, I dont usually practise streams but when I tried to make one, opening my file created with this code I always get random numbers, chars, symbols and trash in the .txt file created. Like this: Hellothere.txt. I see random symbols, character instead of numbers entered, the name is OK because it shows well, but sometimes when I write long names it will write trash.
Can you help me to solve this?, Here's the code:
struct sample {
int code;
char name [20];
} sampl;
int main () {
cout<<" ENTER CODE : "<<endl;
cin>>sampl.code;
cout<<" ENTER NAME :"<<endl;
gets(sampl.name);
fflush(stdin);
FILE *fp;
fp=fopen("Hellothere.txt", "rb+");
if(fp==NULL) {
fp=fopen("Hellothere.txt","wb+");
if(fp==NULL) {
puts("CANNOT OPEN");
return 0;
}
}
fwrite(&sampl,sizeof(sampl),1,fp);
fclose(fp);
getchar();
}
You're mixing C++ and older C facilities for input and output. You'll have a much easier time if you stick to just C++.
First, let's replace your struct with the C++ equivalent:
struct sample {
int code;
std::string name;
};
Now name
can hold as many characters as necessary.
We'll now write a function which will output a sample
to a C++ output stream:
std::ostream& write_sample(std::ostream& os, const sample& samp)
{
os << samp.code << "\n" << samp.name;
return os;
}
This will output the code followed by the name, with a newline in between them.
Now let's modify your main()
routine to use C++ facilities to fill the struct:
int main()
{
sample samp;
cout << "ENTER CODE :\n";
cin >> samp.code;
cost << "ENTER NAME :\n";
cin >> samp.name;
}
Now, we can quickly check whether we've got things right by using our write_sample()
function with std::cout
, which is a type of output stream:
write_sample(std::cout, samp);
This should repeat what you entered out to the console.
To write to a file instead, we can use C++ facilities to open a file stream:
std::ofstream outfile{"Hellothere.txt"};
Now, we can again use our write_sample()
function with this new stream:
write_sample(outfile, samp);
And when your program runs, Hellothere.txt should contain the text you entered.
As a final (slightly more advanced) touch, you might want to rename your write_sample()
function to operator<<
, which will allow you to use the standard <<
streaming style:
outfile << samp;
Put it all together and the final code should look like this:
#include <fstream>
#include <iostream>
#include <string>
struct sample {
int code;
std::string name;
};
std::ostream& operator<<(std::ostream& os, const sample& samp)
{
return os << samp.code << "\n" << samp.name;
}
int main()
{
using namespace std;
sample samp;
cout << "Enter code:\n";
cin >> samp.code;
cout << "Enter name:\n";
cin >> samp.name;
std::ofstream outfile{"Hellothere.txt"};
outfile << samp;
}