我是初学者,正在学习 C++。当我尝试运行此代码的 exe 文件时,它会在我输入第二个数字后按“enter”后立即关闭。如何暂停我的代码以查看结果? 我也试过 system("pause"),它有效,但我读到它只适用于 Windows,使用它被认为是不好的做法,所以我想以正确的方式来做。请帮助
Print.h(我在主代码中使用的头文件)
#pragma once
#include <iostream>
template<typename T> void print(T arg, int newline=1)
{
if (newline)
std::cout << arg << std::endl;
else
std::cout << arg;
}
#include <iostream>
#include <string>
#include "../Print.h"
void calculator()
{
print("Enter the first number: ", 0);
int num1;
std::cin >> num1;
print("Choose Operation (+ - x /): ", 0);
std::string operation = "";
std::cin >> operation;
print("Enter the second number: ", 0);
int num2;
std::cin >> num2;
if (operation == "+") {
print("Output ==> ", 0);
print(num1 + num2);
}
else if (operation == "-") {
print("Output ==> ", 0);
print(num1 - num2);
}
else if (operation == "x") {
print("Output ==> ", 0);
print(num1 * num2);
}
else if (operation == "/") {
print("Output ==> ", 0);
print(num1 / num2);
}
else {
print("Error: Invalid Operation!\nPlease try again.");
calculator();
}
}
int main()
{
print("Welcome!\nLets start!!");
calculator();
std::cin.get();
}
这里有一个可能的方法来做你所要求的
std::cin.ignore(INT_MAX, '\n'); // ignore any pending input
std::cin.get(); // now wait for some new input
初学者忘记的是,在阅读完一些内容后可以留下输入。下次您阅读某些内容时,留下的输入仍然存在,它不会消失。
您可以在
here阅读
ignore
方法