【发布时间】:2019-05-25 15:45:15
【问题描述】:
只要用户继续输入文本,程序就会从用户那里得到几个单词(数字未知),然后将它们打印成一个列表。
假设用户输入了一些单词:
Aang Kyoshi Shirin Farhad Parand Kamran
输出应该是:
[Aang, Kyoshi, Shirin, Farhad, Parand, Kamran]
我已经写下了这段代码:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string current;
int counter = 1;
while (cin >> current)
{
if (counter == 1)
cout << '[' << current << ", ";
else
cout << current << ", ";
counter = counter + 1;
}
cout << ']' << endl;
return 0;
}
结果如下:
cout << current << ", ";
我应该怎么做才能不打印最后一个,?
对于第 17 行:
cout << ']' << endl;
代码如何退出while循环?它不会以Enter、Ctrl+Z 或Ctrl+D 退出循环,因此第 17 行没有执行?!
【问题讨论】:
-
如果在同一行输入单词,首先读取该行,然后使用字符串流提取单词
-
如果您在 Windows 上使用
Ctrl+Z来结束标准输入,您需要在此之后按Enter,因为Ctrl+Z被视为一个字符,只有在输入行。
标签: c++