Reading input from text file to array in c++

前端 未结 2 1881
星月不相逢
星月不相逢 2021-01-29 09:36

Alright, be gentle, since I\'m very much a novice to programming. So far I\'ve only studied C++ and I\'m running Visual Studio 2010 as my compiler. For this program, I\'m trying

相关标签:
2条回答
  • 2021-01-29 09:43

    fstream's getline function has these signatures.

    std::istream& getline (char* s, streamsize n );
    std::istream& getline (char* s, streamsize n, char delim );
    

    In your code...

    string nameAr[EMP_NUM];
    // stuff...
    inFile.getline(nameAr[i], EMP_NUM, "*");
    

    You are trying to use a std::string where getline wants a char* - you cannot convert from string to a char* like this.

    One approach is you can use a character buffer to store the contents of getline, like this.

    const int BUFFER_SIZE = 1024;
    char buffer[BUFFER_SIZE];
    inFile.getline(buffer, BUFFER_SIZE, '*');
    // more stuff...
    

    A better solution

    I'd recommend using std::getline from <string>, as you can use string types instead of C-strings.

    #include <string>
    
    // stuff...
    std::getline(inFile, nameAr[i], '*');
    

    edit Links for you since you are learning

    • std::getline function example
    • std::getline function description
    0 讨论(0)
  • 2021-01-29 09:46

    It appears that you have a pointer problem. You are trying to store a pointer to a char array in nameAr[], correct? What you need to do is define nameAr[] as an array of pointers to char arrays so that you can store a pointer to each name in the nameAr[] array.

    Try using this for your name array instead of nameAr[].

    nameAr = new char*[EMP_NUM];
    
    0 讨论(0)
提交回复
热议问题