首页 > 解决方案 > 如何将 .txt 获取的变量发送到类函数?

问题描述

我需要一些关于类函数的帮助,因为无论我尝试什么都给了我错误。我尝试创建包含我的主要变量的指针,但即使我阅读了很多主题并观看了有关它们的视频,仍然无法弄清楚。我的逻辑有问题,但实际上找不到。在我得到我的数组后,我想在课堂部分使用它们。例如,当我将 case 切换为 0 时,我想显示所有联系人。为此,我必须将我的数组带入课堂,但我不能。我将使用它们来编辑、添加或删除它们。所以我也需要我的柜台。就像我说的。如果有办法有人可以请至少给我一个例子吗?非常感谢。

#include <iostream>
#include <string>
#include <conio.h>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
void printline(char, int);

class person{
private:

int order;
string name;
string surname;
string phonenumber;

public:
    void setName(string isim){
        name=isim;
    }
    string getName(){
        return name;
    }
    void setSurname(string soyad){
        surname=soyad;
    }
    string getSurname(){
        return surname;
    }
    void setPhonenumber(string numara){
        phonenumber=numara;
    }
    string getPhonenumber(){
        return phonenumber;
    }
    

    
};




int main() {
person kisi;
FILE* myFile;
int i = 0;
int j = 0;
int k = 0;
int choice;
int mOrder;
char* mName[20],mSurname[20],mPhone[20];
myFile = fopen("phoneData.txt", "r");
if (myFile != NULL)
    while (fscanf(myFile, "%d%s%s%s", &mOrder, mName, mSurname, mPhone) != EOF)
        i++;
fclose(myFile);
// this is where we find i and now i can create my arrays.

int *orderArray;
char *nameArray[i];
char *SurnameArray[i];
char *PhoneArray[i];
orderArray = (int *) malloc(i * sizeof(int));
   
for (int n=0;n<i;n++)
{
    nameArray[n] = (char*) malloc(20 * sizeof(char));
    SurnameArray[n] = (char *) malloc(20 * sizeof(char));
    PhoneArray[n] = (char *) malloc(20 * sizeof(char));
}

myFile = fopen("phoneData.txt", "r");
if (myFile == NULL)


  {

        printf("There is no file.\n");
}
else 
{
int m=0;
    while (fscanf(myFile, "%d%s%s%s", &orderArray[m], nameArray[m], SurnameArray[m], PhoneArray[m]) != EOF){
        m++;            //this is the part where we read the txt file correctly and seperate it into the parts. 
    }

    fclose(myFile);    
    
    //i made this part just to see if my arrays work or not. They worked.
    /*
        for (int j=0;j<i;j++)
{
    cout<<orderArray[j]<<" "<<nameArray[j]<<"  " << SurnameArray[j]<<"  "<<PhoneArray[j]<<endl;
} 
*/

}


// menü burası olacak

/*
cout << "--- Welcome to the PhoneBook ---" << endl;
printline('-', 32);
cout << "0. Show all the contacts on PhoneBook" << endl;
cout << "1. Add a contact to PhoneBook" << endl;
cout << "2. Search a contact on PhoneBook" << endl;
cout << "3. Edit a contact on PhoneBook" << endl;
cout << "4. Delete a contact from PhoneBook\n" << endl;
cout << "Please make a choice: " << endl;
cin >> choice;
*/


//switch cases will be there.


/*   

 switch(choice){
        case 0:
            showContacts();
        break;
    
    case 1:
        addContacts();
    break;
    
    case 2:
        searchContacts();
    break;
    
    case 3:
        editContacts();
    break;
    
    case 4:
        deleteContacts();
    break;
    
}
*/
return 0;
}


void printline(char ch, int size)
{
    for(int i=0; i<size; i++)
        cout << ch;
    cout << "\n";
}

标签: c++stringreadfile

解决方案


请将此作为可能的数百万其他解决方案的一个示例。

稍后我将编辑答案并进行解释和评论。现在我需要做其他事情

#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <string>

struct Person {

    unsigned int index{};
    std::string name{};
    std::string surname{};
    std::string phoneNumber{};

    friend std::istream& operator >> (std::istream& is, Person& p) {
        if (std::string line{}; std::getline(is, line)) {
            std::istringstream iss{ line };
            iss >> p.index >> p.name >> p.surname >> p.phoneNumber;
        }
        return is;
    }
    friend std::ostream& operator << (std::ostream& os, const Person& p) {
        return os << p.index << '\t' << p.name << '\t' << p.surname << '\t' << p.phoneNumber;
    }
};

struct PhoneBook {
    std::vector<Person> persons{};

    friend std::istream& operator >> (std::istream& is, PhoneBook& p) {
        p.persons.clear();
        std::copy(std::istream_iterator<Person>(is), {}, std::back_inserter(p.persons));
        return is;
    }
    friend std::ostream& operator << (std::ostream& os, const PhoneBook& p) {
        std::copy(p.persons.begin(), p.persons.end(), std::ostream_iterator<Person>(os, "\n"));
        return os;
    }
};

struct PhoneBookAdministration {
    PhoneBook phoneBook{};
    std::string phoneBookFileName{};

    void load(const std::string& fileName) {
        phoneBookFileName = fileName;
        if (std::ifstream phoneBookFileStream(fileName); phoneBookFileStream)
            phoneBookFileStream >> phoneBook;
        else std::cerr << "\nError: Could not open " << fileName << "\n\n";
    }
    void saveAs() {
        std::cout << "\n\nSave As\n\nPlease enter a filename:\n";
        if (std::string fileName{}; std::cin >> fileName) {
            phoneBookFileName = fileName;
            save();
        }
    }
    void save() const {
        if (std::ofstream phoneBookFileStream(phoneBookFileName); phoneBookFileStream) {
            phoneBookFileStream << phoneBook;
        }
        else std::cerr << "\nError: Could not open " << phoneBookFileName << "\n\n";
    }
    void show() const {
        std::cout << "\n\nContents of phone book:\n" << phoneBook << "\n\n";
    }
    void addEntry() {
        std::cout << "\n\nAdd entry to phone book\nEnter name, surname and phone number:\n";
        if (std::string n{}, s{}, p{}; std::cin >> n >> s >> p)
            phoneBook.persons.emplace_back(phoneBook.persons.size(), n, s, p);
    }
    
    void searchContact() const {
        std::cout << "\n\nSearch entry in phone book\nEnter name to search for:\n";
        if (std::string n{}; std::cin >> n) {
            if (auto pos = std::find_if(phoneBook.persons.begin(), phoneBook.persons.end(), [&n](const Person& p) {return p.name == n; }); pos != phoneBook.persons.end())
                std::cout << "\n\nPerson '" << n << "' found:\n" << *pos << '\n';
            else std::cout << "\n\nPerson '" << n << "' not found\n";
        }
    }
    void editContact() {
        std::cout << "\n\nEdit contact. Here is the phone book\n" << phoneBook << "\n\nPlease enter the index of an entry:\n";
        if (size_t index{}; std::cin >> index && index < phoneBook.persons.size()) {
            std::cout << "\n\nEnter name, surname and phone number:\n";
            if (std::string n{}, s{}, p{}; std::cin >> n >> s >> p)
                phoneBook.persons[index] = { phoneBook.persons[index].index, n, s, p };
        }
        else std::cout << "\n\nError, problem with given index\n";
    }
    void deleteContact() {
        std::cout << "\n\nDelete contact. Here is the phone book\n" << phoneBook << "\n\nPlease enter the index of an entry:\n";
        if (size_t index{}; std::cin >> index && index < phoneBook.persons.size()) 
            phoneBook.persons.erase(phoneBook.persons.begin() + index);
    }
};

int main() {
    PhoneBookAdministration pba{};
    pba.load("r:\\pb.txt");


    bool runProgram{ true };
    while (runProgram) {
        // Show menu
        std::cout <<
            "\n\n\nMain Menu\n"
            "You have the follwing options:\n"
            "   1 - Save\n"
            "   2 - Save as\n"
            "   3 - Show\n"
            "   4 - Add Entry\n"
            "   5 - Search\n"
            "   6 - Edit entry\n"
            "   7 - Delete entry\n"
            "   0 - Exit program\n\n"
            "Please select:\n";

        if (int selection{}; std::cin >> selection) {
            switch (selection) {
            case 1:
                pba.save();
                break;
            case 2:
                pba.saveAs();
                break;
            case 3:
                pba.show();
                break;
            case 4:
                pba.addEntry();
                break;
            case 5:
                pba.searchContact();
                break;
            case 6:
                pba.editContact();
                break;
            case 7:
                pba.deleteContact();
                break;
            case 0:
                std::cout << "\n\nExiting . . .\n\n";
                runProgram = false;
                break;
            default:
                std::cout << "\n\nWrong selection. Please try again\n";
                break;
            }
        }
        else std::cerr << "\n\nError: Problem with selection\n";
    }
    return 0;
}

推荐阅读