-2

I have the following text file from which I am attempting to read each line and then store the integer component and the string component separately. Here is the text file:

RUID Name 
4325 name1
RUID Name  
5432 name2 
6530 name3
RUID Name 
1034 name4 
2309 name5

Here is the code I attempting to read with:

int main()
{
    // Initialize Lists
    LinkedList list1, list2, list3; 

    // Initialize Counter
    int counter = 0; 


    // Entry containers
    const int size = 12; 
    char entry[size];
    string name[size]; 
    string RUID[size]; 

    // BEGIN: "read.txt" 
    // Open 
    ifstream studDir; 
    studDir.open("read.txt");
    // Read
    while (studDir.is_open())
    {
        if (studDir.eof())
        {
            cout << "Reading finished" << endl;
            break;
        }

        else if (!studDir)
        {
            cout << "Reading failed" << endl;
            break;
        }

        studDir.getline(entry, size);


        if (entry != "RUID Name")
        {
            cout << entry << " " << endl;
        }

    }


    return 0;
}

Could anyone recommend a method that would allow me to ignore the "RUID Name" line as well as separate the integer and string portion of the relevant lines. I've tried several strategies with little success. Also I wish to then write the output of the sorted list to a text file.

Daniel
  • 66
  • 1
  • 9

1 Answers1

1

You should rewrite your loop like this:

// Entry containers
const size_t size = 12; 
std::string entry;
string name[size]; 
string RUID[size]; 
size_t index = 0;

// ...

while (index < size && std::getline(studDir,entry)) {
    if (entry != "RUID Name") {
        cout << entry << " " << endl;
        std::istringstream iss(entry);
        if(!(iss >> RUID[index] >> name[index])) {
            std::cout << "Reading failed" << endl;
            break;
        }
        ++index;
    }
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190