Thread: Reading strings from a file and storing into an array

  1. #1
    Registered User
    Join Date
    Aug 2002
    Posts
    16

    Reading strings from a file and storing into an array

    As the subject states, I'm trying to read a string of text from file and store it into an array. The text file is structured as follows:

    Albert
    Bobby
    Harry
    Terl
    ...

    I've tried much code, but I can't seem to get it to store inside an array for later recall. I would post some code, but it wouldn't be of any benefit since it's just completely wrong. All I get when I scan in the file is just the letters, like this:

    a
    l
    b
    e
    r
    t
    ...

    How can I structure the array to make it store, then print out the whole word and not just the letters?

  2. #2
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    One easy way is to use strings and a vector....read a line into a string and push it onto the vector.....maybe not the most efficient way...but simple

    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <vector>
    
    
    int main (int nArg,char* szArg[]){
    
    	if(nArg < 2){
    		std::cout << "Only pass the name of the file!" << std::endl;
    		return 1;
    	}
    		
    	std::ifstream in(szArg[1]);
    	if(!in.is_open()){
    		std::cout << "Couldnt open the file!" << std::endl;
    		return 1;	
    	}
    	
    	std::vector<std::string> vec;
    	std::string str;
    	
    	while(!in.eof()){
    		getline(in,str);
    		vec.push_back(str);
    	}
    	
    	for(int i = 0;i < vec.size();i++)
    		std::cout << vec[i] << std::endl;
    	
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help - Reading a file and storing it as a 2d Array.
    By MetallicaX in forum C Programming
    Replies: 2
    Last Post: 03-08-2009, 07:33 PM
  2. reading file and storing to arrays
    By dayknight in forum C Programming
    Replies: 4
    Last Post: 04-27-2006, 05:17 AM
  3. Reading all the numbes from a file and storing in an array
    By derek tims in forum C++ Programming
    Replies: 2
    Last Post: 04-02-2006, 03:01 PM
  4. Replies: 5
    Last Post: 10-02-2005, 12:15 AM
  5. Trouble storing file input in array
    By difficult.name in forum C Programming
    Replies: 1
    Last Post: 10-10-2004, 11:54 PM