Reading Comma Delimited Text File Into Array

前端 未结 2 645
北荒
北荒 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: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 
    #include 
    #include 
    #include 
    
    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<<"\""< enrolled;
                std::string course;
                while( std::getline(ss,course,',') )
                {
                     enrolled.push_back(course); std::cout<<", \""<

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

提交回复
热议问题