| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Two Small Problems With Simple File I/O
Hello,
I'm in the process of learning C++ and am quite enthusiastic as to how well it's been coming along. I do have a little problem where I'm at, right now. Shown below is the source I'm working with: Code:
// user defined filehandle
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string user_filename, user_input;
unsigned int line_count;
cout << "Filename to open for writing: ";
getline(cin, user_filename);
ofstream user_filehandle (user_filename.c_str());
cout << "Begin typing the data you want stored into " << user_filename
<< endl << "Type EOF on a single line when finished" << endl;
while(1) {
if(user_input == "EOF") break;
line_count++;
getline(cin, user_input);
user_filehandle << user_input << endl;
fflush(stdin);
}
user_filehandle.close();
cout << "Wrote " << line_count << " lines to " << user_filename << endl;
cin.get();
return 0;
}
Problem #1 Now for some reason or other, the line_count integer data type variable is counting up to some insanely high number instead of properly tallying and accounting for the number of lines the user is writing to the filehandle. Problem #2 I can't seem to prevent the program from writing the very last user input, "EOF" to the filehandle. Any help would be greatly appreciated. Thanks! Best Regards, Matt Mr. Mattly Networks Visit us at http://www.mrmattly.net/ |
|
#2
|
|||
|
|||
|
For problem #1 : The counter will give high value becuse you have put conditions like that.
To be clear: You are just askinh the user to enter a word.Hence even if he presses "Enter" and comes to next line, that will be taken as a word and so counter will be incremented . Ex: Suppose i enter few words as shown: " My Name " , as it is a one line , your program outputs it as 2 lines since I have not entered "EOF" . Remember , I have entered two string in a line.Your code takes "Enter" or "Return Key" as character.Therefore for each word you type, counter is updated. For second part: What do you mean by you can't prevent input as EOf?? Last edited by Cirus : March 23rd, 2006 at 07:00 PM. |
|
#3
|
|||
|
|||
|
Figured it out
Quote:
No, actually initializing line_count(0) fixed it. Thanks anyways! |
|
#4
|
|||
|
|||
|
Quote:
But line_count is a variable of scalar type . How can you initialize like this??? It ain't a class. |
|
#5
|
|||
|
|||
|
by doing usigned int line_count(0);
I tried it. If I left out the (0), then it gives me the insanely high number. But when I start with 0, it then counts up properly. Don't ask me how it works, but I tested it, and it works. I don't know, maybe it's a Dev-C++ thing. |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > Two Small Problems With Simple File I/O |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|