【问题标题】:How to take delimiter as -0 between array size and array value of integer in c++如何在c ++中将数组大小和整数数组值之间的分隔符设为-0
【发布时间】:2020-10-17 15:11:34
【问题描述】:

如何在c++中将数组大小和整数数组值之间的分隔符设为-0。

for example: 2 -0 1,2 -0
array-size '-0' 1st array values separated by "," '-0'

如果我使用 get line 在字符串中输入,那么如何从字符串中分离大小并输入数组。

int main(){

string s,t;

getline(cin,s);

stringstream x(s);

while(getline(x,t,"-0")){
    cout << t;
}

}

我无法从 google 正确理解分隔符的概念,您能否解释一下并输入:“array-size '-0' 1st array values separator by ',''-0'” 形式。

【问题讨论】:

标签: c++ delimiter


【解决方案1】:

根据输入,最简单的方法是将字符串标记检查为-0 分隔符。

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

using std::cin;
using std::cout;
using std::getline;
using std::string;
using std::stringstream;

int main(){
    string s,t;
    getline(cin, s);
    stringstream x(s);
    char const* sep = "";
    while (x >> t) {
        if (t == "-0") {
            cout << sep << "<DELIMITER>";
        } else {
            cout << sep << t;
        }
        sep = " ";
    }
    cout << "\n";
}

这给了:

echo '2 -0 1,2 -0' | ./a.out
2 <DELIMITER> 1,2 <DELIMITER>

更新

将值存储到std::vector&lt;int&gt;

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

using std::cin;
using std::cout;
using std::getline;
using std::ostream;
using std::runtime_error;
using std::size_t;
using std::stoi;
using std::string;
using std::stringstream;
using std::vector;

static auto MakeVecInt(string line) -> vector<int> {
    auto result = vector<int>();
    auto ss = stringstream(line);
    auto value = string{};

    while(getline(ss, value, ',')) {
        result.push_back(stoi(value));
    }

    return result;
}

static auto operator<<(ostream& out, vector<int> const& v) -> ostream& {
    char const* sep = "";

    for (auto i : v) {
        out << sep << i;
        sep = " ";
    }

    return out;
}

int main() {
    auto line = string{};
    getline(cin, line);
    auto ss = stringstream(line);

    auto count = size_t{};
    auto delimiter1 = string{};
    auto values = string{};
    auto delimiter2 = string{};

    if (!(ss >> count >> delimiter1 >> values >> delimiter2))
        throw runtime_error("bad input");

    if (delimiter1 != "-0" || delimiter2 != "-0")
        throw runtime_error("bad input");

    auto vec = MakeVecInt(values);

    if (count != vec.size())
        throw runtime_error("bad input");

    cout << vec << "\n";
}

更新

注意上面代码中的vector&lt;int&gt;输出例程:

static auto operator&lt;&lt;(ostream&amp; out, vector&lt;int&gt; const&amp; v) -&gt; ostream&amp;

它输出向量中的每个元素,每个元素之间有一个空格。它不会在第一个元素之前输出空格。

【讨论】:

  • 请不要让你的生活变得过于艰难。那些使用声明和函数声明语法的人不必要地使提供的示例复杂化。或者这种效果是有意的?
  • @moooeeeep • 这是故意的。我更喜欢发布完整的示例,而不是假定 C++ 新手能够自己填补空白的 sn-ps。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-19
  • 1970-01-01
  • 2012-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多