Download your favorite Linux distribution at LQ ISO.
Go Back > Forums > Non-*NIX Forums > Programming
User Name
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.


  Search this Thread
Old 09-17-2007, 11:44 PM   #1
LQ Newbie
Registered: Dec 2006
Distribution: Slackware 11
Posts: 7

Rep: Reputation: 0
C++ Text File into String Array

I know this is probably on the site, but the search function ticks me off.

I have a text file /etc/vhosts

How do I load each line of the text file into an array?

string vhosts[30];

This way when we update vHosts we can just modify the file it reads from without having to recompile.

I can do this via shell script, easily, but when I can use C++ for something on the box I try to.

The data is going to look like this - -

Old 09-18-2007, 12:05 AM   #2
LQ Addict
Registered: Jul 2003
Location: London, UK
Distribution: Slackware
Posts: 7,464

Rep: Reputation: Disabled
You can use getline(istream &i, string &s) to read lines from an istream, i into a string variable, s (you'll need to include <string> for that function). You can use a for loop to go through the elements of the array.
Old 09-18-2007, 03:59 AM   #3
Registered: Sep 2004
Posts: 273

Rep: Reputation: 30
Why an array? Use a vector instead and let it handle the fact that the number of lines can vary.

Untested sample code:
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
   ifstream infile("filename.ext");

   if (!infile)
      cerr << "Could not open file." << endl;

      return 1;

   vector<string> lines;
   string line;

   while (getline(infile, line))


   // Do whatever with the lines

   return 0;


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
How to replace a string in a text file jpan Linux - General 3 10-14-2012 06:17 PM
C++ text file line by line/each line to string/array Dimitris Programming 15 03-11-2008 08:22 AM
c++ file string from text file into 1d array ak3 Programming 16 12-29-2006 09:45 AM
How to pick a string from a text file? sdandeker Linux - General 1 02-12-2004 04:17 AM
Parsing a file for a string of text jamesmwlv Linux - General 2 12-02-2002 07:13 PM > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 04:09 AM.

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration