|
-
December 1st, 2010, 12:25 PM
#1
reading the last char twice
I am not going to type in all my code, but when I run the program it reads the last char twice.How can I fix it thank you
Code:
void main()
{
ifstream fin;
ofstream fout;
string temp;
char* pch;
char* array[100];
int count= 0;
fin.open("tvshows.dat");
if(fin.fail()) {
cout << "Could not open" << endl;
exit(1);
}
while(!fin.eof())
{
fin>>temp;
pch = (char *) malloc(sizeof(char) * temp.size());
strcpy(pch, temp.c_str());
array[count++] = pch;
}
-
December 1st, 2010, 12:29 PM
#2
Re: reading the last char twice
Stop using eof() to control a loop like that. Rather, just write:
Code:
while (cin >> temp)
By the way, void main should be int main, and you should improve your indentation. Also, although it does not matter in this case, you should generally prefer to use new over malloc, yet in this case you might as well just use std::string.
-
December 1st, 2010, 12:34 PM
#3
Re: reading the last char twice
This is a common error. The more foolproof approach is:
Code:
while(fin>>temp)
{
pch = (char *) malloc(sizeof(char) * temp.size());
strcpy(pch, temp.c_str());
array[count++] = pch;
}
Well, really the *most* foolproof approach would be (extending beyond just file writing now)
Code:
int main()
{
ofstream fout;
vector<string> strs;
ifstream fin("tvshows.dat");
if(!fin)
{
cerr << "Could not open" << endl;
return 1;
}
string temp;
while(fin>>temp)
{
strs.push_back(temp);
}
This demonstrates several "best practices":
1) Don't explicitly check stream state, just see whether anything has gone wrong by implicitly converting the stream to bool.
2) Prefer vectors to fixed-size arrays if you aren't going to include bounds-checking.
3) Don't mix std::strings with char arrays unless you absolutely have to (rare).
4) Prefer not to use malloc in a C++ program.
5) Main always returns int.
6) Don't call exit() yourself.
7) Declare variables as close as possible to the point of first use.
8) Stick to one form of brace positioning throughout.
9) Don't use "array" as a variable name, it could conflict with std::array.
10) Prefer cerr to cout for printing error messages.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|