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

标签 c++ arrays string c++11 int

有人会帮助我理解以下代码中 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/

相关文章:

C++ 参数化 header 包含

javascript - 当尝试发送给用户数组时,meteor.js email.send 不起作用

javascript - 将图像添加到我的阵列?

c++ - 第一个字符串元素的地址产生意外结果

javascript - 如何在不破坏 HTML 标签的情况下将空格转换为 &nbsp?

c++ - 带有模板化访客的访客模式

c++ - "The C Compiler [...] is not able to compile a simple test program"使用 CMake 和 Android NDK

c++ - Cmake target_link_libraries 没有链接我的库

c++ - 我的数组中突然有额外的索引值

java - 验证字符串仅包含逻辑运算符和一些条件