[C++] Reading text file into a struct.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Sara J
    New Member
    • Feb 2012
    • 2

    [C++] Reading text file into a struct.

    Hello Codecall.

    First post and all. I'm having a little trouble here with a program I'm currently writing.
    Basically I want to read data from text-file into two variables in a struct.

    The text file is formated in the following way:

    var1 [TAB] var2

    The problem occurs when var2 is longer than one word and it doesn't really read the data into the struct.
    Anyhow, would really appreciate some help or be pointed in the right direction.

    Here's the textfile.
    Code:
    DVD	Kidmovie 1
    Blu-Ray	Spam Kings 2000
    VHS	The Short Road
    Here's my program.

    Code:
    #include "stdafx.h"
    #include <iostream>
    #include <string>
    #include <vector>
    #include <fstream>
    
    using namespace std;
    struct movieData{
    	string mType;
    	string mName;
    };
    
    void writeData(vector<movieData>& inData);
    
    int main()
    {
        vector<movieData> inData;
    	writeData(inData);
    	
    	
    	system("Pause");
        return 0;
    }
    
    
    void writeData(vector<movieData>& inData){
    
    	
    	ifstream inFile;
    	inFile.open("filmdb.txt");
    		if (!inFile){
    			cout << "Could not find the file.\n";
    		}
    		else{
    			inData.clear();
    			movieData tmpData;
    			while (getline(inFile, tmpData.mName) && getline(inFile, tmpData.mType)){ 
    			
    		
    			inData.push_back(tmpData);					
    			}
    		}
    
    	//(getline(inFil, tmpData.mName) && getline(inFil, tmpData.mType))
    	//inFil >> tmpData.mType >> tmpData.mName	
    		
    
    		if (inData.empty()){
    			cout << "\nNo data found!\n";
    			}
    		else{
    			cout << "\nWriting output:\n";
    			for (int i = 0; i < inData.size(); i++){
    				cout << inData.at(i).mType << '\t' << "- " << inData.at(i).mName << endl;
    			}
    		}
    	}
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    The >> operator stops on whitespace. So it will stop on the space after the frst word.

    To read an entire buffer of some length use getline().

    Comment

    Working...