Solved

How Do I  Read Text File into Array using C++

Posted on 2009-07-09
15
702 Views
Last Modified: 2012-05-07
Im really unfamiliar with C++ so need some help. Can someone post the exact code that will do the following;

I have a  text file called "C:\\bob.txt"

It contains 256 rows of 3 digits (separated by a space). ie. the first 3 lines are

33 47 50
12 88 99
44 90 23

Each number contains a maximum of 3 digits.
 
Each row represents a colour in RGB format. ie 1st number is red, 2nd number is green, 3rd number is blue.

I want to read the text file into an array of Color. Something along the lines of;

Color myColorArray = new Color[256];

Then you would use a loop and add each line of 3 digits (representing a color) to the array. ie.

Color col  = Color::FromArgb(r,g,b);

then add col to the array


So basically I need to read the text file and add each line that represents a color to an array of Color.
Can someone post the exact code that would do this?

Thanks
0
Comment
Question by:rangers99
  • 5
  • 5
  • 4
  • +1
15 Comments
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 24812059
Something like the below?
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
using namespace std;
 
 
...
ifstream ifs("bob.txt");
string line;
vector<Color> colors;
while (getline(ifs, line))
{
    istringstream iss(line);
    Color c = { 0 };
    if (!iss >> c.red) continue;
    if (!iss >> c.green) continue;
    if (!iss >> c.blue) continue;
    colors.push_back(c);
}
ifs.close();

Open in new window

0
 
LVL 40

Expert Comment

by:evilrix
ID: 24812097
http://www.cplusplus.com/reference/algorithm/copy/
http://www.cplusplus.com/reference/stl/vector/
http://www.cplusplus.com/reference/std/iterator/istream_iterator/
http://www.cplusplus.com/reference/iostream/fstream/
http://www.cplusplus.com/reference/iostream/stringstream/
#include <sstream>
#include <string>
#include <vector>
#include <iterator>
 
struct Color // Dummy
{
   Color(int r, int g, int b)
      :r(r), g(g), b(b)
   {}
 
   int r;
   int g;
   int b;
};
 
int main()
{
   // For test purposes I use a stringstream you can swap this for
   // a fstream to read the same data from file, interfaces are identical
   std::stringstream ifs("33 47 50\n12 88 99\n 44 90 23");
 
   std::string sLine;
   std::vector<int> v(3);
   std::vector<Color> colors;
 
   while(std::getline(ifs, sLine))
   {
      std::stringstream ss(sLine);
      std::copy(std::istream_iterator<int>(ss), std::istream_iterator<int>(), v.begin());
 
      colors.push_back(Color(v[0], v[1], v[2]));
   }
}

Open in new window

0
 

Author Comment

by:rangers99
ID: 24812106
Hi
Did that code compile OK?
I tried pasting that into my code but Im getting several compiler errors.
0
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 

Author Comment

by:rangers99
ID: 24812112
Sorry my above comment was for "itsmeandnobodyelse"
0
 
LVL 40

Expert Comment

by:evilrix
ID: 24812113
>> Did that code compile OK?
Me or Alex?

Me -- yes, of course :)
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 24812121
>>     if (!iss >> c.red) continue;

Be careful with operator precedence. This does something entirely different than what you intended, since the negation operator (!) has higher precedence than the bit-leftshift operator (<<). You should add ()'s :

        if (!(iss >> c.red)) continue;
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 24812140
>>>> Did that code compile OK?
Hmmm, I made some "..." which probably won't compile.

also the code below the includes should be moved to a function or to your main.

Then I assumed Color struct has members red, green, blue. If it is not or if it is r,g,b  you would need to change it.

Best, you post the struct definition of Color and I could test it on my system.
0
 

Author Comment

by:rangers99
ID: 24812143
evilrix
The Color struct you have defined clashes with the Color class
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 24812148
>>>> if (!(iss >> c.red)) continue;
Thanks, Infinity. I recognized it after posting.
0
 
LVL 40

Expert Comment

by:evilrix
ID: 24812151
>> The Color struct you have defined clashes with the Color class
It's for example purposes only... that's why it says Dummy next to it. I am not compiling this on Windows so it is meant to represent your Color class.
0
 
LVL 40

Expert Comment

by:evilrix
ID: 24812156
>> I am not compiling this on Windows so it is meant to represent your Color class.
In other words swap it out for your class.
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 24812163
>>>> Me -- yes, of course :)
>>>> I am not compiling this on Windows

yes, of course ;-)
0
 
LVL 40

Accepted Solution

by:
evilrix earned 250 total points
ID: 24812178
Just noticed you need to use FromArgb... code modified to suit.

>>> colors.push_back(Color::FromArgb(v[0], v[1], v[2])); <<<

NB. Again, Color is a dummy class since I don't have Windows... just remove it and use your own class.
#include <sstream>
#include <string>
#include <vector>
#include <iterator>
 
struct Color // Dummy
{
   Color(int r, int g, int b)
      :r(r), g(g), b(b)
   {}
 
   static Color FromArgb(int r, int g, int b)
   {
      return Color(r,g,b);
   }
 
   int r;
   int g;
   int b;
};
 
int main()
{
   // For test purposes I use a stringstream you can swap this for
   // a fstream to read the same data from file, interfaces are identical
   std::stringstream ifs("33 47 50\n12 88 99\n 44 90 23");
 
   std::string sLine;
   std::vector<int> v(3);
   std::vector<Color> colors;
 
   while(std::getline(ifs, sLine))
   {
      std::stringstream ss(sLine);
      std::copy(std::istream_iterator<int>(ss), std::istream_iterator<int>(), v.begin());
 
      colors.push_back(Color::FromArgb(v[0], v[1], v[2]));
   }
}

Open in new window

0
 

Author Closing Comment

by:rangers99
ID: 31601504
Thanks thats done it. cheers.
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 24812223
The below compiles on my compiler.

I will test later.
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
using namespace std;
 
/*  it is only for my test 
    you should use your Color structure
 
struct Color
{
   int r, g, b;
   static Color FromArgb(int red, int green, int blue)
   {
      Color c = { 0 };    
      c.r = red; c.g = green; c.b = blue;
      return c;
   }
};
*/
 
bool getColors(vector<Color>& colors)
{
   ifstream ifs("bob.txt");
   string line;
   while (getline(ifs, line))
   {
       istringstream iss(line);
       int red = 0, green = 0, blue = 0;
       if (!(iss >> red)) continue;
       if (!(iss >> green)) continue;
       if (!(iss >> blue)) continue;
       // Hope FromArgb was no typo
       Color c = Color::FromArgb(red, green, blue);
       colors.push_back(c);
   }
   ifs.close();
   return colors.size() != 0;
}
 
int main(void) 
{
   vector<Color> colors;
   if (getColors(colors))
   {
      // here you can use the array
   }
   return 0;
}
 

Open in new window

0

Featured Post

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question