gpt4 book ai didi

c++ - 从控制台获取多个字符串并将它们写为 C++ 中的列表

转载 作者:太空宇宙 更新时间:2023-11-04 15:11:48 25 4
gpt4 key购买 nike

只要用户继续输入文本,程序就应该从用户那里得到几个单词(数量未知),然后将它们作为列表打印出来。

假设用户输入了一些单词:

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;
}

结果如下:

enter image description here第 14 行:

cout << current << ", ";  

我应该怎么做才能不打印最后一个,

对于第 17 行:

cout << ']' << endl;  

代码将如何退出 while 循环?它不会使用 EnterCtrl+ZCtrl+D 退出循环,所以第 17 行没有执行?!

最佳答案

这是一个没有if、没有标志、没有分支的实现:

#include <iostream>
#include <sstream>
#include <string>

int main()
{
std::string line;
std::getline(std::cin, line);
std::istringstream stream{line};
std::string s;
stream >> s;
std::cout << "[ " << s;
while (stream >> s)
{
std::cout << ", " << s;
}
std::cout << " ]";
}

关于c++ - 从控制台获取多个字符串并将它们写为 C++ 中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56306354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com