if statements with strings not returning true and entering if statement

trying to get the program to close if the user inputs "exit" for filename but the if statement isn't returning true and the code just skips over it (sorry for the bad formatting this is my first post)


#include<iostream>
#include<fstream>
#include<iomanip>
#include<cstdlib>
#include<string>

using namespace std;

int main()
{

string filename = "hello";
ifstream fin;
int count = 0;
int arr[9] = { 0 };


cout << " ~Word Counter~ " << endl;
cout << "What file would you like a report on (or type exit to quit): ";
cin >> filename;

if (filename == "exit")
{
exit;
}

fin.open(filename);

while (fin.fail() == 1)
{
cout << "File " << filename << " could not be found." << endl;
cout << "What file would you like a report on (or type exit to quit): ";
cin >> filename;

if (filename == "exit")
{
exit;
}
}

char ch = fin.get();

do
{
count = 0;


while (ch != 32 && static_cast<int> (ch) != -1)
{
count++;
ch = fin.get();
}

ch = fin.get();
arr[count-1]++;

} while (!fin.eof());

fin.close();

cout << "~~~~~Word Count for Test.txt~~~~~" << endl;
cout << " Length:" << setw(8) << "Count:" << endl;

for (int i=0; i< 8; i++)
{
cout << setw(11) << i+1 << setw(8) << arr[i] << endl;
}

cout << setw(11) << ">8" << setw(8) << arr[8] << endl;
}
Last edited on
exit; does not call a function.

It's exit(1); (or some other return code).

But you should avoid using exit. It's from C, and doesn't account for C++ stack unwinding (automatic destruction of objects). Prefer to just return from the function.
e.g.
return 0; to indicate success from main,
return 1; or some other non-zero value to indicate failure from main.
Last edited on
cool thank you
Topic archived. No new replies allowed.