gpt4 book ai didi

c++ - 在C++中将字符串转换为整数数组

转载 作者:行者123 更新时间:2023-11-27 23:49:54 28 4
gpt4 key购买 nike

有人会帮助我理解以下代码中 while 循环的作用吗?例如,从用户那里获取输入:1 2 3 8(未给出输入大小)和一个值(任何索引)显示数组的大小。它正在打印数组的最大值。这里的答案是 8。

#include<bits/stdc++.h>
#define ll long long
using namespace std;
int main()
{
int t;
cin >> t;
while(t--)
{
string x;
getline(cin, x);
ll p;
istringstream iss(x);// use of this function
vector<ll> v;
ll ans;
while(iss>>p)// what this loop do
{
v.push_back(p);
}
ll size=v.size()-1;
sort(v.begin(), v.end());
if(size==v[size])
{
ans=v[size-1];
}
else
{
ans=v[size];
}
cout<<ans<<"\n";
}
return 0;
}

最佳答案

istringstream iss(x) 创建一个名为 iss 的字符串流,由字符串 x 组成。 iss >> p 从 iss 流中提取下一个元素并将其放入 p 中。返回值为int,因为变量p是int类型。

while(iss>>p)           // get an int value from string stream iss
{
v.push_back(p); // push the int value to the vector
}

你必须在 cin 之后使用 cin.ignore()。否则下一个 getline 函数将只接受换行符。像这样:

cin >> t;
cin.ignore();

关于c++ - 在C++中将字符串转换为整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47259503/

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