0

I am writing this program that allows the user to input their name, and it puts it to a file. this, however does not work. it only takes in the name, and does nothing! it also only runs the first if statement.

#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <Windows.h>

using namespace std;

class user{
public:
    string name;
    int userID = rand() % 1001;

    void setName(string n) { name = n; };
    string getName() { return name; };
    int returnID() { return userID; };
};

int main() {
    HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
    string udef;
    user mat;
    int id = mat.returnID();

        while (udef != "exit" || "Exit") {
            SetConsoleTextAttribute(h, FOREGROUND_BLUE | FOREGROUND_GREEN |        FOREGROUND_INTENSITY );
            cout << "Type a command to continue. You may also type help for   a list of commands." << endl << "User: ";
            getline(cin, udef);
            if (udef == "new" || "New") {
                cout << "Type your name:" << endl << "User: ";
                getline(cin, udef);
                mat.setName(udef);
                ofstream userfile(id + ".txt");
                if (userfile.is_open()) {
                    cout << "Generating User info file..." << endl;
                    Sleep(10);
                    cout << "File Name : '" << id << "'" << endl;
                    userfile << mat.getName();
                    Sleep(10);
                    cout << "Appending information..." << endl;
                    cout << "Done! " << mat.getName() << " has been written to line(s) 1 of " << id << ".txt!" << endl;
                }
                userfile.close();
            }
            else if (udef == "help" || "Help") {

            }
        }

    return 0;
}
max66
  • 65,235
  • 10
  • 71
  • 111

1 Answers1

1

Try with

while ( (udef != "exit") && (udef != "Exit") ) 

instead of

while (udef != "exit" || "Exit") 

A plain and simple "Exit" is ever true and udef is ever different from Exit or exit.

P.s.: obviuosly, same problem (and similar correction) with

if (udef == "new" || "New") 

and with

else if (udef == "help" || "Help") 

They become

if ( (udef == "new") || (udef == "New") ) 

and

else if ( (udef == "help") || (udef == "Help") ) 
max66
  • 65,235
  • 10
  • 71
  • 111
  • Or use one of the [toupper() methods on this page](https://stackoverflow.com/questions/735204/convert-a-string-in-c-to-upper-case) and have, for example, `while (boost::to_upper(udef) != "EXIT")` – Ken Y-N Jan 13 '17 at 02:39
  • 1
    @KenY-N - reasonable; but I trying to explain where the error is, more than propose a better solution. – max66 Jan 13 '17 at 02:41
  • Of course - correcting the `||` misunderstanding is probably more useful at this point in the OP's development. – Ken Y-N Jan 13 '17 at 02:56