gpt4 book ai didi

c++ - do...while() 重复最后一个字符串两次

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:06:49 27 4
gpt4 key购买 nike

以下代码将提供的字符串/行拆分为字符。为什么循环重复最后一个字符串两次?如何解决?

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

using namespace std;

int main()
{
string main, sub;
cout << "Enter string: ";
getline(cin, main);
istringstream iss(main);
do
{
iss >> sub;
cout << sub << endl;
vector<char> v(sub.begin(), sub.end());
for(int i = 0; i < v.size(); i++)
{
cout << v[i] << endl;
}
} while (iss);
return 0;
}

输入:

hello world

期望的输出

hello
h
e
l
l
o
world
w
o
r
l
d

实际输出:

hello
h
e
l
l
o
world
w
o
r
l
d
world
w
o
r
l
d

我已经尽可能删除了与问题无关的元素

最佳答案

在最后一次运行中,iss 引发了一个失败,因此 sub 的值没有更新,从而导致重复发生。一种查看方式是在 do 循环开始时将 sub 设置为空字符串。为了避免这种问题,我会做类似下面的事情

while(iss>>sub){
cout<<sub<<endl;
etc
}

另外,我想指出的是,您可以遍历字符串,因为它可以被视为 char*,因此您不需要 vector 转换的东西。

关于c++ - do...while() 重复最后一个字符串两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35416182/

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