【问题标题】:Need help taking a line from a text file and sorting that line into multiple variables需要帮助从文本文件中提取一行并将该行排序为多个变量
【发布时间】:2020-10-09 04:00:52
【问题描述】:

我正在尝试从文本文件中获取名称和 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;

【问题讨论】:

标签: c++ hex rgb


【解决方案1】:

您必须逐行读取文件并使用 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
}

【讨论】:

    【解决方案2】:

    我假设您似乎在解析输入行以获取颜色名称 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, 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();
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多