是否为此添加退出语句



这是我的问题。我必须从控制台读取一行,例如:

Name,Area,Cost

然后使用逗号作为分隔符,它必须命名、面积和成本,并将它们放入相应的变量中,以放入哈希表中。然后使用循环,程序需要连续执行此操作,直到用户键入退出语句以退出循环。它添加到变量中很好,但当我键入exit时,它只是等待我认为是分隔符的字符。但即便如此,它也不会退出。

以下是迄今为止的全部代码:

while (true) {
getline(cin, name, ',');
if (name == "exit") {
break;
}
getline(cin, area, ',');
cin >> cost;

//code to see if the variables are placed
cout << "results" << endl;
cout << name << endl;
cout << area << endl;
cout << cost << endl;

}
//code to check for exit
cout << "Loop has exited" << endl;

默认情况下,std::getline()读取,直到遇到'n'(Enter(或EOF(在Windows上Ctrl-Z*Nix上Ctrl-D等(。如果指定除'n'之外的分隔符,它将不再停止对'n'的读取。因此,当用户键入exit并按下Enter时,getline(cin, name, ',');不会停止读取,只有当用户键入一个','字符(或Ctrl-Z/Ctrl-D(时才会停止读取。

您应该首先使用带有默认'n'分隔符的std::getline()将用户的整个输入读取到std::string中,直到键入Enter,然后检查该字符串是否为"exit",如果不是,则可以根据需要使用std::istringstream来解析该字符串,例如:

#include <string>
#include <sstream>
std::string line, name, area;
double cost;
while (std::getline(std::cin, line) && (line != "exit"))
{
std::istringstream iss(line);
std::getline(iss, name, ',');
std::getline(iss, area, ',');
iss >> cost;

//code to see if the variables are placed
std::cout << "results" << std::endl;
std::cout << name << std::endl;
std::cout << area << std::endl;
std::cout << cost << std::endl;
//add to heap command
}
//code to check for exit
std::cout << "Loop has exited" << std::endl;

最新更新