0

I`m trying to take a name and 3 numbers from a text file then take that input and store the name into color and the 3 numbers into r,g,b then it will take the r,g,b numbers and turn them into hex color codes.the text file format is as follows

color1 190 190 190

color2 20 50 70

This following code is where my problem lies

ifstream ReadFile; 
ReadFile.open(filename); 

if(ReadFile.fail()) 
{
cout<<"Could not open "<<filename<<endl;
}
else
{
   while ( getline (ReadFile,line) )
        {
            cout << line << '\n';
        }


}
//for(string line; getline(ReadFile, line, '.'); ) 
//{
//cout<<line<<endl;

//}
ReadFile.close();


//cout<<"Enter the value of RGB(from range 0 to 255):";
    cin>>r>>g>>b;
    cout<<rgbtohex(r,b,g,true)<<endl;
273K
  • 29,503
  • 10
  • 41
  • 64

2 Answers2

1

You have to read file line by line and tokenize that line with space delemeter

std::ifstream file("fileName");
std::string   line;

while(std::getline(file, line))
{
    std::stringstream   linestream(line);
    std::string         data;
    std::string         color;
    int                 r;
    int                 g;
    int                 b;

    // If you have truly space delimited data use getline() with third parameter.
    // If your data is just white space separated data
    // then the operator >> will do (it reads a space separated word into a string).
    // so no need to third params
    std::getline(linestream, data);  
    // example of comma delemeter
    //std::getline(linestream, data,','); 
    // Read the integers using the operator >>
    linestream >> r>> g>>b;
    // and before calling close file file you have store all r,g,b value other wise 
    //process within this loop
}
Roshan M
  • 511
  • 4
  • 14
1

I assume you seems to be having issue parsing the input line to get the color name, r, g, b values as your code for reading from text file is correct. For that, you can use istringstream object (iss) to get the values for multiple variables of different types separated by spaces from each file line

#include<iostream> 
#include <fstream>
#include <sstream>

using namespace std;

int main () {
  string filename = "colors.txt"; // Color input file
  ifstream ReadFile; 
  istringstream iss;
  ReadFile.open(filename); 
  string line, color;
  int r, g, b;

  if(ReadFile.fail()) {
    cout<<"Could not open "<<filename<<endl;
  }
  else {
    while (getline (ReadFile,line)) {
      iss.clear();
      iss.str(line);
      iss >> color >> r >> g >> b;
      cout << "Color: " << color << endl;
      cout << "R: " << r << endl;
      cout << "G: " << g << endl;
      cout << "B: " << b << endl;
    }
    ReadFile.close();
  }
}
VietHTran
  • 2,233
  • 2
  • 9
  • 16