如何解决需要帮助,请从文本文件中提取一行并将该行排序为多个变量
我正在尝试从文本文件中获取一个名称和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
}
,
我认为您似乎在解析输入行以获取颜色名称r
,g
,b
值时遇到问题,因为从文本文件读取的代码是正确的。为此,您可以使用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();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。