#include <iostream>
int main() {
std::cout << "Please enter two numbers" << std::endl;
int v1, v2 = 0;
std::cin >> v1 >> v2;
std::cout << "The sum of " << v1 << " and " << v2
<< " is " << v1 + v2 << std::endl;
std::cin.get();
return 0;
}
我添加了cin.get(),以便在关闭之前我可以在终端中看到结果,但由于某种原因,程序在打印结果后仍然会立即关闭。有没有更好的方法来阻止窗口在运行代码后立即关闭?
答案 0 :(得分:1)
std::cin >> v1 >> v2;
此时您输入内容,例如:
4 5 <Enter>
(使用<Enter>
键生成换行符。)
第一个>>
解析&#34; 4&#34;。
第二个>>
解析&#34; 5&#34;。
您对get()
的来电会读取换行符'\n'
。
然后你的程序立即终止。
使用std::getline()
从终端而不是>>
运算符中读取以交互方式输入的文本行。这是std::getline()
的用途。