求助!cin如何导致cout输出自动换行?

李纪玺 2014-02-06 03:55:14
一般来说,cout输出是不会自动换行的。例如:

#include <iostream>
using namespace std;
int main() {
cout << "ONE!";
cout << "TWO!" << endl;
return 0;
}

这段代码的输出格式如下:
ONE!TWO!

即使在两条cout语句之间有其他语句,输出也不会自动换行:

#include <iostream>
int main()
{
using namespace std;
int carrots;
cout << "How many carrots do you have?" << endl;
cin >> carrots; // C++ input
cout << "Here are two more. ";
carrots = carrots + 2;
// the next line concatenates output
cout << "Now you have " << carrots << " carrots." << endl;
return 0;
}

上述代码摘自C++ Primer Plus 6ed, P45。

输出结果为
How many carrots do you have?
12
Here are two more. Now you have 14 carrots.
Here are two more.与Now you have 14 carrots.之间并无自动换行。

但是,在How many carrots do you have?与Here are two more. 之间只是有一个cin语句,并没有类似endl的东西,为什么这两句不位于同一行中呢?例如:
How many carrots do you have?12Here are two more. Now you have 14 carrots.

如果要做到上述输出效果,应如何做呢?请达人指点。多谢。
...全文
237 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
李纪玺 2014-02-06
  • 打赏
  • 举报
回复
不好意思,写错了。应该是cout << "How many carrots do you have?"
李纪玺 2014-02-06
  • 打赏
  • 举报
回复
不好意思,写错了。应该是cout << "How many carrots do you have?" << endl;
taodm 2014-02-06
  • 打赏
  • 举报
回复
cout << "How many carrots do you have?" << endl; 天哪,这个让人说啥好呢?

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧