需要帮助,请从文本文件中提取一行并将该行排序为多个变量

问题描述

我正在尝试从文本文件中获取一个名称和3个数字,然后输入该名称并将名称存储为颜色,并将3个数字存储为r,g,b,则它将获取r,g,b个数字和将它们转换为十六进制颜色代码。文本文件格式如下

color1 190 190 190

color2 20 50 70

下面的代码是我的问题所在

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;

解决方法

您必须逐行读取文件,并使用 space 删除符

对该行进行标记
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
}
,

我认为您似乎在解析输入行以获取颜色名称rgb值时遇到问题,因为从文本文件读取的代码是正确的。为此,您可以使用istringstream对象(iss)来获取不同类型的多个变量的值,这些变量的每个文件行之间用空格隔开

#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,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();
  }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...