C++ 为什么我的控制台应用程序不等待第37行和第38行?
这个问题需要帮助。当我运行可执行文件时,控制台没有给我时间按照第37行的要求输入字符,我无法识别问题。只有当我注释掉两个for循环时,它才起作用。代码如下所示:C++ 为什么我的控制台应用程序不等待第37行和第38行?,c++,C++,这个问题需要帮助。当我运行可执行文件时,控制台没有给我时间按照第37行的要求输入字符,我无法识别问题。只有当我注释掉两个for循环时,它才起作用。代码如下所示: #include "../../std_lib_facilities.h" #include "../../Eigen/Eigen" #include "../../Eigen/Dense" #include <Windows.h> #include <time.h> using namespace Eigen
#include "../../std_lib_facilities.h"
#include "../../Eigen/Eigen"
#include "../../Eigen/Dense"
#include <Windows.h>
#include <time.h>
using namespace Eigen;
int main()
{
SetConsoleTitle(TEXT("PipeThk_v1.0"));
system("CLS");
system("color F1");
time_t rawtime_start;
struct tm * timeinfo_start;
time(&rawtime_start);
timeinfo_start = localtime(&rawtime_start);
printf(asctime(timeinfo_start));
cout << "\nEnter nominal pipe sizes in 'in':\n";
vector<double> npss;
for (double nps; cin >> nps;)
npss.push_back(nps);
cout << "\n NPS\n";
for (const auto& i : npss)
cout << "\n " << i;
time_t rawtime_end;
struct tm * timeinfo_end;
time(&rawtime_end);
timeinfo_end = localtime(&rawtime_end);
cout << endl << endl << asctime(timeinfo_end);
cout << "\nEnter any character and hit enter to exit:\n";
char ans;
cin >> ans;
return 0;
}
#包括“../../std_lib_facilities.h”
#包括“../../Eigen/Eigen”
#包括“../../Eigen/Dense”
#包括
#包括
使用名称空间特征;
int main()
{
SetConsoleTitle(文本(“PipeThk_v1.0”);
系统(“CLS”);
系统(“颜色F1”);
开始时间;
struct tm*timeinfo\u start;
时间(&rawtime_start);
timeinfo\u start=localtime(&rawtime\u start);
printf(asctime(timeinfo_start));
cout>nps;)
nps。推回(nps);
cout您正在使用operator>
将std::cin
解析为double
变量
操作员>>
遇到无法转换的字符时停止读取输入。该字符(如按Enter或空格键)将保留在流的缓冲区中,并立即可供第37行上的操作员>
读取,而无需提示用户进行更多输入
因此,例如,如果输入47
并按Enter键获取最后一个double
值,则值47
将解析为double
变量,并且回车键将被std::cin>>ans作为\n
字符读取
今天的教训是:不要使用operator>
处理来自终端的std::cin
的交互式输入。使用std::getline()
要一次读取一行文本,然后根据需要构造一个std::istringstream
对象来解析该行。将每次出现的std::cin>…
替换为std::getline(std::cin)
,以避免解析交互式输入时出现意外情况
当然,这不是做这件事的唯一方法,但它需要最少的工作量,并导致最少的意外行为。这不是你的问题,但你不需要让cin
等待char
,你可以简单地使用std::cin.get();
使用系统(“暂停”)
如果您在Windows上,请查看为什么不建议使用35、36和37。可能的重复:使用运算符>>
直接从std::cin
读取输入没有错。您只需清除其缓冲区,在读取最后一个字符之前清除所有挂起的数据,它就会等待在用户方面,例如:cin.clear();cin.ignore(numeric_limits::max(),'\n');cin>>ans/*或cin.get()*/;
我遵循了刷新缓冲区解决方案,因为我没有看到任何其他更干净的方法来收集我的nps
向量的数据,而没有操作符>
。我还必须使用cin.ignore(10000,\n'))
相反,因为我在max()部分下收到了一些关于预期和标识符的错误消息。@Remy Lebeau您能对此发表评论吗?@PipeTran Sam为您提供了一个更干净的解决方案-使用std::getline()
读取行并std::istringstream
解析每行。您可以在std::istringstream
上使用运算符>
。对于数值限制
错误,请使用包含
。