Hello!
I am trying put a string to the file "test.dat" using "switch". File exist and empty.
Program shows
Enter a string (CR to quit)
I start typing the string and program is closed immediately. If the file isn't exist all the same. Program "takes off". What should I change for in my code in order to correct the problem?
I start typing the string and program is closed immediately.
The immediate problem is that after cin >> input; there will be a trailing newline character remaining in the input buffer, which causes problems with the subsequent entering of a string. That can be fixed by inserting this just after line 16:
cin.ignore(1000, '\n');
This will ignore up to 1000 characters from cin, or until a the delimiter '\n' is found.
However, there are other problems; at line 20 the file is opened for input but at line 25 the program tries to output to the file.
There is also an unseemly mix of C and C++ style i/o, and the use of outdated headers.
Here's a simplified version of the program, using C++ i/o.
Two reasons:
1. there is a trailing '\n' in the input buffer after cin >> input;
2. the program attempts to write output to a file which was opened for input (read only).
But it is necessary to realize algorithm of the problem.
Could you describe what algorithm you are supposed to implement, it isn't clear.
But it is necessary to realize algorithm of the problem.
in answer to Darehow post. And a code scheme of the first post is realized now according your recommendations of cin.ignore and replacing fp = fopen("TEST.dat", "r"); to fp = fopen("TEST.dat", "a");
Thanks again!