cin.get()不起作用
我今天写了这个简单的程序,但是我发现 cin.get()
拒绝工作,除非有两个。有什么想法吗?
I wrote this simple program today, but I found that cin.get()
refuses to work unless there are 2 of them. Any ideas?
#include <iostream>
using namespace std;
int main(){
int base;
while ((base < 2) || (base > 36)){
cout << "Base (2-36):" << endl;
cin >> base;
}
string base_str = "0123456789abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < base; i++){
for (int j = 0; j < base; j++){
for (int k = 0; k < base; k++){
cout << base_str[i] << base_str[j] << base_str[k] << endl;
}
}
}
cin.get();
cin.get();
}
如果我移动 cin.get()
到嵌套循环之前,循环将运行然后暂停。如果我取出一个 cin.get()
,该程序就结束了。我正在使用最新版本的流血c ++ dev
if i move a cin.get()
to before the nested loops, the loops run then pause. if i take one cin.get()
out, the program just ends. im using the latest version of bloodshed c++ dev
您没有初始化'base'变量,但这会导致错误它与cin的行为无关(直接),即使有时(取决于编译器)会导致您跳过循环。
You are not initializing the 'base' variable, but while that will cause bugs it isn't (directly) related to the behavior you're seeing with cin, even though it will sometimes, depending on the compiler, cause you to skip loops. You're probably building in debug mode that zero-initializes or something.
话虽如此,但假设已修复:
That said, assuming that was fixed:
当您键入一个值(例如5)并按Enter键时,流中的数据为 5< newline>
-运算符<不会从流中提取换行符,但是cin.get()会提取。您的第一个cin.get()从流中提取该换行符,而第二次等待则等待输入,因为该流现在为空。如果只有一个cin.get()调用,它将立即提取换行符并继续,并且由于在cin.get()调用之后没有任何内容,程序将终止(应有的终止)。
When you type a value (say, 5) and hit enter, the data in the stream is 5<newline>
-- operator<< does not extract the newline from the stream, but cin.get() does. Your first cin.get() extracts that newline from the stream, and the second wait waits for input because the stream is now empty. If you had only the one cin.get() call, it would extract the newline immediately and continue, and since there is nothing after that cin.get() call, the program terminates (as it should).
似乎从调试器运行时,您正在使用cin.get()阻止程序关闭;您通常可以通过IDE中的特定无需调试即可启动命令来执行此操作;那么您就不需要为此而滥用cin.get()。
It seems that you're using cin.get() to stop your program from closing when run from the debugger; you can usually do this via a specific "start without debugging" command from your IDE; then you won't need to abuse cin.get() for this purpose.