返回信息流#include <iostream>
int main()
{
std::cout<<"输入两个数"<<std::endl;
int a,b,h,l;
std::cin>>a>>b;
if(a>=b){
h=a;
l=b;
}
else{
h=b;
l=a;
}
int count=0;
for(int i=l;i<=h;++i){
count++;
if(count<10)
std::cout<<i<<" ";
else{
std::cout<<"\n"<<i<<" ";
count=0;
}
}
return 0;
}
为什么第一行输出的数是9个就换行了,其他的都是10个
这是一条镜像帖。来源:北邮人论坛 / cpp / #88951同步于 2015/10/2
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
让每行输出数据不超过10个
bingge
2015/10/2镜像同步6 回复
订阅后,新回复会通过你的通知中心匿名送达。
6 条回复
秀一下最近学的boost::coroutine。比多线程快,比状态机容易写。
#include <cstdio>
#include <boost/coroutine/asymmetric_coroutine.hpp>
using namespace std;
using namespace boost::coroutines;
typedef asymmetric_coroutine<int> coro_int;
class FinalEOL {
int *p;
public:
FinalEOL(int *ptr_cur_in_line): p(ptr_cur_in_line) {}
~FinalEOL() {
if (*p > 0) { // print a '\n' if the line is not empty
printf("\n");
}
}
};
void ten_per_line(coro_int::pull_type &in) {
int cur_in_line = 0;
FinalEOL ensureEOL(&cur_in_line); // In its destructor, print a '\n' when this coroutine is killed.
while(in) {
int next = in.get();
if (cur_in_line > 0) { // Print ' ' before a number, except the first in a line.
printf(" ");
}
printf("%d", next);
cur_in_line++;
if (cur_in_line == 10) { // Print '\n' after every 10 numbers.
cur_in_line = 0;
printf("\n");
}
in(); // Read the next number.
}
// ~EnsureEOL destructor called when dying.
}
int main() {
{
coro_int::push_type printer(ten_per_line);
for(int i = 0; i < 42; i ++) {
printer(i);
}
}
return 0;
}
编译:把上述代码存成boost-ten-per-line.cpp, 然后
c++ -l boost_system -l boost_coroutine -o boost-ten-per-line boost-ten-per-line.cpp
输出:
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41
因为后面每行的第一个数据来自你上次循环输出/n后的那个i,如果你把std::cout << "\n" << i << " ";改成std::cout<<"\n"<<" ";那就是每行9个,就都公平啦
【 在 bingge 的大作中提到: 】
: 可是后边的怎么都是10个