在C ++中用定界符-1分隔数组的大小和数组值

问题描述

用定界符-1分隔数组的大小和数组的值

输入的形式:

Array-size -1 array-values(separated by,) -1 number -1
3 -1 3,5,7 -1 6 -1

不要使用向量,将值放入用户给定的大小数组中,否则打印“ -1”。

我已经尝试过此代码,但无法完成它:

#include <iostream>
#include <string>
    
using namespace std;
    
int main(){
    string s{};
    getline(cin,s)
    stringstream ss(s);

    string count = size_t{};
    string delimiter1 = string{};
    string value = string{};
    string delimiter2 = string{};
    string size = string{};
    string delimiter3 = string{};

    if(!(ss >> count >> delimiter1 >> values >> delimiter2 >> size >> delimiter2))
        cout << -1 << endl;

    if(delimiter1 != "-1" || delimiter2 != "-1" || delimiter3 != "-1")
        cout << -1 << endl;

    int a[1000];

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

解决方法

您的代码似乎还没有达到一百万英里,但是您尚未对values进行下标,并且在错误的位置使用了ss delimiter2,并且您尝试在数组上使用delimiter3

其他错误是将整数值读取为字符串,这似乎在为自己做更多的工作。

最后,由于您知道必须读取多少个整数,因此您可能应该使用该信息。

这段代码看起来更近

push_back
,

我认为很多代码都可以。如果输入格式错误或-1很大,它将在stderr上打印n

#include <iostream>
#include <istream>
#include <string>

int main() {
  try {
    int n,_,number;
    std::string str;
    std::cin.exceptions(std::istream::failbit);
    std::cin >> n >> _;
    int *arr = new int[n];
    for (int i = 0,temp; i < n; ++i) {
      std::cin >> temp;
      arr[i] = temp;
      std::cin >> std::ws;
      std::cin.ignore();
    }
    std::cin >> _ >> number >> _;
    // do something with array and number
    for (int i = 0; i < n; ++i)
      std::cout << arr[i] << ' ';
    std::cout << '\n' << number;
  } catch (...) {
    std::cerr << -1;
  }
}

示例运行:https://wandbox.org/permlink/hfcXf4BTXQSwCiVm