简体   繁体   中英

Classes reading one word from file C++

This is my program and it supposed to get text word by word from file Team.txt but it says it can't open the file. I tried showing directory directly to the file still the same answers. I think I got something here:

class Team
    {
        public:
        string name;
        string dificulty;
        string section;
    };



void GetTeamInfo(class Team);

    int main()
    {   
        Team ko;
        GetTeamInfo(ko);
        cout << ko.name;
        cout << ko.dificulty;
        cout << ko.section;
        system("PAUSE");
    }

void GetTeamInfo(Team)
    {
        std::ifstream fd;
        fd.open("Team.txt");
        Team ko;
        if (fd.is_open())
        {
            fd >> ko.name;
            fd >> ko.dificulty;
            fd >> ko.section;

        }
        else
        {
            std::cout << "Mistake can't open file 'Team.txt'\n";
        }
    }

It doesn't work because your argument handling is all wrong.

The declaration

void GetTeamInfo(Team)

tells the compiler that GetTeamInfo is a function which takes an argument of type Team , but you don't give it a name so you can't use the argument anywhere inside the function.

If you want to use the passed argument you should give it a name:

void GetTeamInfo(Team ko)

You then don't have to declare the variable ko inside the function.

However, this is not going to work anyway, because arguments are by default passed by value , that means arguments are copies of the values from the caller. And changing a copy will of course not change the original. So what you should do it pass the argument by reference :

void GetTeamInfo(Team& ko)

All of this is very basic C++ knowledge, and any good book or tutorial should have learned you this very early.


As for the problem of the program not being able to open your file, there are multiple possible causes for that problem:

  • Your IDE (Integrated Development Environment) is having one current directory for your program, and the file is not in that directory. This can be changed with project settings.

  • The file is actually not where you think it is.

  • The file simply doesn't exist.

  • On systems such as Linux and Mac OSX filenames are case sensitive, and the actual file doesn't have a capital 'T' in its name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM