Reputation: 537
I have created a program that creates a file of the users name and then allows them to insert lines. I want to make it so that if they enter nothing (just pressing enter) it exits, but I have trouble figuring out what I'm doing wrong. Here is my code:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
char filename[20];
char line[81];
int X;
cout<<"Welcome to a very primative word precessor"<<endl;
cout<<"please enter a filename"<<endl;
cin.getline(filename, 19);
ofstream file_out(filename, ios::app);
if (! file_out){
cout<<"Cannot open "<<filename;
cout<<"!!!"<<endl;
return -1;
}
cout<<"File "<<filename;
cout<<" was opened."<<endl;
do {
cout<<"Enter your notes here"<<endl;
cin.getline(line, 80);
file_out<<line<<endl;
cout<<line<<endl;
}
while (! line);
cout<<"last line"<<endl;
file_out.close();
return 0;
}
Upvotes: 2
Views: 213
Reputation: 38
It's just your while condition that needs to be changed:
while (strlen(line) != 0);
Upvotes: 2
Reputation: 455380
The problem is with the way you are comparing line
:
do {
cout<<"Enter your notes here"<<endl;
cin.getline(line, 80);
...
}
while (! line);
^^^^^^^
! line
is same as line == 0
. Now line
is the address of the char array:
char line[81];
So that comparison is always false as line
will always evaluate to true.
You need to change it to:
while (! strcmp(line,""));
and add a
#include <cstring>
at the beginning.
Upvotes: 2