【发布时间】:2011-10-16 12:20:29
【问题描述】:
我需要在开头阅读带有特定关键字的多行。 我有一个基本问题,需要帮助。
下面是输入的种类:
关键字1 0.0 0.0
关键字1 1.0 5.0
关键字2 10.0
关键字3 0.5
关键字4 6.0
规则是:
包含关键字 1 和关键字 2 的行应按此顺序排列,并且在任何其他行之前。
包含关键字 3 和关键字 4 的行可以是任意顺序
keyword1 必须后跟 2 个双精度字
关键字 2、3 和 4 必须后跟 1 个双精度字
在包含所有四个关键字及其双精度的行的末尾,“循环”中断并触发计算。
这是我的来源:
using namespace std;
int main (int argc, const char * argv[]) {
vector<double> arrayInputs;
string line;
double keyword1_first, keyword1_second, keyword4,
keyword3, keyword2;
bool inside_keyword1=false, after_keyword2=false,
keyword4_defined=false, keyword3_defined=false ;
//cin.ignore();
while (getline(cin, line)) {
if (inside_keyword1 && after_keyword2 && keyword3 && keyword4) {
break;
}
else
{
std::istringstream split(line);
std::vector<std::string> tokens;
char split_char = ' ';
for (std::string each; std::getline(split, each, split_char); tokens.push_back(each));
if (tokens.size() > 2)
{
if (tokens[0] != "keyword1") return EXIT_FAILURE; // input format error
else
{
keyword1_first = atof(tokens[1].c_str());
keyword1_second = atof(tokens[2].c_str());
inside_keyword1 = true;
}
}
else
{
if (tokens[0] == "keyword2")
{
if (inside_keyword1)
{
keyword2 = atof(tokens[1].c_str());
after_keyword2 = true;
}
else return EXIT_FAILURE; // cannot define anything else keyword2 after keyword1 definition
}
else if (tokens[0] == "keyword3")
{
if (inside_keyword1 && after_keyword2)
{
keyword3 = atof(tokens[1].c_str());
keyword3_defined = true;
}
else return EXIT_FAILURE; // cannot define keyword3 outside a keyword1
}
else if (tokens[0] == "keyword4")
{
if (inside_keyword1 && after_keyword2)
{
keyword4 = atof(tokens[1].c_str());
keyword4_defined = true;
}
else return EXIT_FAILURE; // cannot define keyword4 outside a keyword1
}
}
}
}
// Calculation
// output
return EXIT_SUCCESS;
}
我的问题是:除了在读取/解析循环中使用布尔值之外,还有更有效的方法吗?
【问题讨论】:
-
你定义了你的“问题”(就像你布置了一个任务或任务一样),你提供了来源,但你还没有向读者指出一个问题 为我们。你有什么问题?
-
非常抱歉。问题是:是否存在另一种更有效的方法,而不是在读取/解析循环中使用布尔值?