Cin newline space problem... or something
For my first C++ program, I made a little text editor for the sake of understanding the whole fopen stuff. With my background knowledge of PHP this is going rather well, but I have encountered a problem.
Code:
#include<iostream.h>
#include<cstdio>
#include<string>
void main () {
cout<<"Welcome to FedEdit...\n";
char filename[255];
cout<<"Please enter the file path to open. \nNote that it will be interpreted as a textfile\nKeep it small, yes?\n";
cin>>filename;
cout<<"You chose "<<filename<<"\n\n";
FILE * filePointer;
filePointer = fopen(filename,"r+");
if(filePointer) {
cout<<"File Contents:\n\n";
char line[81];
char *return_code;
while(!feof(filePointer)) {
return_code = fgets(line, 80, filePointer);
cout<<line;
}
cout<<"\n\n--------------------------\nOkay, now enter new file content:\n";
cout<<"a line only containing a period will end the writing mode.";
cout<<"please do not enter more than 80 characters per line. thank you.\n\n--------------------\n";
char newline[81];
rewind(filePointer);
while(strcmp(newline,".")) {
cin>>newline;
if(strcmp(newline,".")) {
fputs(newline,filePointer);
fputs("\r\n",filePointer);
}
}
fclose(filePointer);
} else cout<<"ERRORZ";
}
this is the source. Basicially, you open a file of choice, it echoes it, and then you re-write it. The problem?
Well, it interprets spaces as newlines. Actually, it doesn't.
Code:
while(strcmp(newline,".")) {
cin>>newline;
if(strcmp(newline,".")) {
fputs(newline,filePointer);
fputs("\r\n",filePointer);
}
}
see that part?
well that's the problem. Apparently, when encountering a space, the loop re-loops with the next word, causing
Code:
fputs("\r\n",filePointer);
to render it as new line.
Now, why is this happening, how do I fix this?
Any other suggestions for a better way of coding are appreaciated as well!
I'm a beginner, sorry.