Reading Comma Delimited Text File Into Array

前端 未结 2 619
北荒
北荒 2021-01-23 12:16

I am trying to write a program in C++ that emulates a college enrollment system, where the student enters their ID, and the program searches a text file for their information, a

相关标签:
2条回答
  • 2021-01-23 12:35
    split(string, seperator)
    
    split("918273645,Steve,Albright,ITCS2530,MATH210,ENG140", ",")
    split("123456789,Kim,Murphy,ITCS2530,MATH101", ",")
    split("213456789,Dean,Bowers,ITCS2530,ENG140", ",")
    split("219834765,Jerry,Clark,MGMT201,MATH210", ",")
    

    I know very little C++, but I remember this command.

    0 讨论(0)
  • 2021-01-23 12:44

    The problem is that std::getline takes exactly one character as a delimiter. It defaults to a newline but if you use another character then newline is NOT a delimiter any more and so you end up with newlines in your text.

    The answer is to read the entire line into a string using std::getline with the default (newline) delimiter and then use a string stream to hold that line of text so you can call std::getline with a comma as a delimiter.

    Something like this:

    #include <fstream>
    #include <sstream>
    #include <iostream>
    #include <vector>
    
    int main()
    {
        std::ifstream inFile("registration.txt");
        if (inFile.is_open())
        {
            std::string line;
            while( std::getline(inFile,line) )
            {
                std::stringstream ss(line);
    
                std::string ID, fname, lname;
                std::getline(ss,ID,',');    std::cout<<"\""<<ID<<"\"";
                std::getline(ss,fname,','); std::cout<<", \""<<fname<<"\"";
                std::getline(ss,lname,','); std::cout<<", \""<<lname<<"\"";
    
                std::vector<std::string> enrolled;
                std::string course;
                while( std::getline(ss,course,',') )
                {
                     enrolled.push_back(course); std::cout<<", \""<<course<<"\"";
                }
                std::cout<<"\n";
            }
        }
        return 0;
    }
    

    In this example I am writing the text to the screen surrounded by quotes so you can see what is read.

    0 讨论(0)
提交回复
热议问题