使用C 从定界线拆分字符串中提取整数数组



我试图从C 中的字符串中提取整数序列,其中包含某个定界符,并与它们创建数组:

输入是以下格式:

<integer>( <integer>)+(<delimiter> <integer>( <integer>)+)+

示例1 2 3 4; 5 6 7 8; 9 10(此处定界符是 ;

结果应该是三个整数数组,包含: [1, 2, 3, 4][5, 6, 7, 8][9, 10]


到目前为止我尝试的是使用istringstream,因为它已经通过 whitespace 将它们分配,但是我没有成功:

#include <iostream>
#include <sstream>
using namespace std;
int main() {
    string token;
    cin >> token;
    istringstream in(token);
    // Here is the part that is confusing me
    // Also, I don't know how the size of the newly created array
    // will be determined
    if (!in.fail()) {
        cout << "Success!" << endl;
    } else {
        cout << "Failed: " << in.str() << endl;
    }
    return 0;
}

我的建议是读取直到使用std::getline';',然后使用std::istringstream解析字符串:

std::string tokens;
std::getline(cin, tokens, ';');
std::istringstream token_stream(tokens);
std::vector<int> numbers;
int value;
while (token_stream >> value)
{
  numbers.push_back(value);
}

拿走上一个答案是读取直到使用 std::getline';',然后使用 std::istringstream将字符串向下解析至其空间:

std::string tokens;
std::getline(cin, tokens);
std::istringstream token_stream(tokens);
std::vector<string> arr;
vector<vector<int>> toReturn
string cell;
while (getline(token_stream, cell, ';')
{
    arr.push_back(cell);
}
for(int i = 0; i<arr.size(); i++)
{
     istringstream n(arr[i]);
     vector<int> temp;
     while(getline(n, cell, ' ') temp.push_back(atof(cell));
     toReturn.push_back(temp);
}

最新更新