Thugnificent
Thugnificent

Reputation: 23

File access not working

I am watching Bucky's tutorials on C++. He made a program and i did exactly as he did but i cannot get the list to work. I can get the txt file to view the objects on a separate program but this program just doesn't wanna view anything. It works and compiles okay but nothing on the screen once a choice input is entered. Selecting 4 does exit the program but the 1,2,3 options don't bring up anything at all.

Here's the video explaining the program: https://www.youtube.com/watch?v=86rBqzYIbjA&index=68&list=PLAE85DE8440AA6B83#t=3.934331

My code:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int getUserData();
void display(int x);


int main(){


    int userdata;

    userdata = getUserData();

    while(userdata =! 4){

        switch(userdata){
            case 1:
                display(1);
                break;
            case 2:
                display(2);
                break;
            case 3:
                display(3);
                break;
            default:

        }
        userdata = getUserData();


    }


}

int getUserData(){

    int choice;

    cout << "Enter 1 to view all the neutral items" << endl;
    cout << "Enter 2 to view all the helpful items" << endl;
    cout << "Enter 3 to view all the harmful items" << endl;
    cout << "Enter 4 to exit" << endl;
    cin >> choice;

    return choice;

}

void display(int x){


    ifstream obj;
    obj.open("prog2.txt");

    string chars;
    int powers;

            if(x==1){
                while(obj>>chars>>powers)
                if(powers==0){
                    cout << chars<<' '<<powers<< endl;

                }
            }

            if(x==2){
                while(obj>>chars>>powers)
                if(powers>0){
                    cout << chars<<' '<<powers<< endl;
                }
            }


            if(x==3){
                while(obj>>chars>>powers)
                if(powers<0){
                    cout << chars<<' '<<powers<< endl;
                }
            }


}

This is getting pretty frustrating and any help at all would be highly appreciated!

Upvotes: 1

Views: 50

Answers (1)

Ton Plooij
Ton Plooij

Reputation: 2641

Your test 'while(userdata =! 4)' is invalid. The 'not is' operator is !=. What the code actually does is while (user data = !4), meaning you're assigning the expression !4 (which is false, hence 0) to userdata. The test condition then evaluates to false and the loop is not entered.

Upvotes: 3

Related Questions