C++ 未在 Xcode 控制台中显示 cout 但在终端中运行完美
C++ not showing cout in Xcode console but runs perfectly in Terminal
基本上我是 运行在 Xcode Version 8.3 (8E162)
中编写一个简单的程序
#include <iostream>
using namespace std;
int main() {
int a;
cout << "What is your age: ";
cin >> a;
cout << "My age is " << a << endl;
return 0;
}
我看到了关于 cout
需要刷新和所有 std::cout won't print and 的不同问题。在我输入 \n or endl
之前,Xcode 调试器不会打印 cout
。但是,它在终端上工作得很好。
如果我必须在单行中使用 What is your age:
和用户输入年龄而不是在下一行输入 \n and endl
怎么办?
这是 Xcode 调试器在构建和 运行
后显示的内容
这是用户输入并显示结果的时候
这是在终端上,这正是我需要在 Xcode 调试器上输出的内容。
您已经自己解决了您的问题:std::cout
使用缓冲输出并且应该始终刷新。您可以通过使用 std::cout << "What is your age? << std::flush
、使用 std::cout.flush()
或添加像 std::endl
这样隐式刷新的换行符来实现此目的。
完整的解决方案可能如下所示:
#include <iostream>
using namespace std;
int main() {
int a;
cout << "What is your age: " << flush;
cin >> a;
cout << "My age is " << a << endl;
return 0;
}
通过一些研究,Mar 27, 2017
发布的 Xcode Version 8.3 Build 8E162
上的 cin and cout
流似乎存在错误。
降级到 Xcode Version 8.2.1
就像一个魅力。
基本上我是 运行在 Xcode Version 8.3 (8E162)
#include <iostream>
using namespace std;
int main() {
int a;
cout << "What is your age: ";
cin >> a;
cout << "My age is " << a << endl;
return 0;
}
我看到了关于 cout
需要刷新和所有 std::cout won't print and \n or endl
之前,Xcode 调试器不会打印 cout
。但是,它在终端上工作得很好。
如果我必须在单行中使用 What is your age:
和用户输入年龄而不是在下一行输入 \n and endl
怎么办?
这是 Xcode 调试器在构建和 运行
后显示的内容这是用户输入并显示结果的时候
这是在终端上,这正是我需要在 Xcode 调试器上输出的内容。
您已经自己解决了您的问题:std::cout
使用缓冲输出并且应该始终刷新。您可以通过使用 std::cout << "What is your age? << std::flush
、使用 std::cout.flush()
或添加像 std::endl
这样隐式刷新的换行符来实现此目的。
完整的解决方案可能如下所示:
#include <iostream>
using namespace std;
int main() {
int a;
cout << "What is your age: " << flush;
cin >> a;
cout << "My age is " << a << endl;
return 0;
}
通过一些研究,Mar 27, 2017
发布的 Xcode Version 8.3 Build 8E162
上的 cin and cout
流似乎存在错误。
降级到 Xcode Version 8.2.1
就像一个魅力。