C++控制台读取不确定数量的输入,并将它们放入数组中

C++ console reading uncertain number of inputs and put them in an Array?

本文关键字:数组 不确定 读取 控制台 输入 C++      更新时间:2023-10-16
  1. 假设以下数字是在VC++控制台中输入的(用空格分隔(。N可能是10、20或100,这是不确定的。

    1 2 3 4 ... N [Enter]

  2. 输入的数量是不确定的,可能是10或20。按下Enter键后,如何将这些数字放入数组?

    array[0]=1; array[1]=2; ...

如何用C++代码实现这一点?

(输入数量不确定!(

正如PeterT所指出的,如果您不提前知道数组的大小,则必须使用动态内存分配。幸运的是,STL有一个容器可以为您完成这项工作。

您可以将std::vector用于该作业。

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
int main() {
    std::string nums; // the numbers in the format "1 2 3 4 10 -20"
    std::getline(std::cin,nums);
    std::stringstream stream(nums);
    int n;
    std::vector<int> vec;
    while(stream >> n) {
        vec.push_back(n);
    }
    return 0;
}

(代码基于Abdulla Al-Sun的答案。(

这是一个O(n((线性复杂度(解。

如果你想把它转换成一个实际的数组,你可以做:

int array[vec.size()];
std::copy(vec.begin(), vec.end(), array);

另一种方法是通过将用户的输入存储在字符串中并对令牌进行计数来计算用户输入了多少元素。

然后你就知道你需要多大的数组了。

unsigned int getSize(std::string s) {
    unsigned int size = 0;
    std::stringstream ss(s);
    int in;
    while (ss >> in)
        ++size;
    return size;
}
int main() {
    std::string nums; // the numbers in the format "1 2 3 4 10 -20"
    std::getline(std::cin,nums);
    const unsigned int size = getSize(nums);
    int array[size];
    std::stringstream stream(nums);
    int n;
    for(unsigned int i = 0; stream >> n && i < size; ++i) {
        array[i] = n;
    }
    return 0;
}

这是一个O(2n((线性复杂度(解。


我的代码假设编译器允许可变数组大小。如果没有,请使用:

int* array = new int[size];
...
delete[] array;

要使用RAII,请将其封装在这样的结构中:

struct DynArr {
    int* data;
    unsigned int size;
    DynArr(const unsigned int size) :
        size(size) {
        data = new int[size];
    }
    ~DynArr() {
        delete[] data;
    }
};
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int array[1000]; // your heighest input range
vector<int> numbers;
int main() {
    string nums; // the numbers in the format "1 2 3 4 10 -20"
    getline(cin,nums);
    stringstream stream(nums);
    int i = 0;
    int n;
    while(stream >> n){
        array[i++] = n;
        numbers.push_back(n);
    }
    // The number of integers in array is i. You can do anything with this number.
    // numbers contains the input numbers.
    return 0;
}

在得到PeterT的想法后,我添加了vector。您可以为不设置数组的静态大小添加矢量。

试试这个代码。字符串流的头是sstream。我已经编译了代码块,我想这也会在VC++编译器上工作。

我将窃取Abdulla的代码,并进行一些轻微的修改。

#include <iostream>
#include <string>
#include <sstream>
#include <cstring.h> // for memcpy
//using namespace std; frowned on. polutes global namespace
//the highest input range is undefined, so this isn't safe
//int array[1000]; // your heighest input range
int main() {
    int max=10;
    int * array = new int[max];// allow resizing of array by dynamically allocating
    std::string nums; // the numbers in the format "1 2 3 4 10 -20"
    std::getline(std::cin,nums);
    std::stringstream stream(nums);
    int i = 0;
    while(stream){
        if (i==max)
        {
            int * temp = new int[max*2];// note statistical analysis has found 
                                        //1.5 is generally a better multiplier
            memcpy(temp, array, max*sizeof(array[0])); 
            // note do not use memcpy for copying complex data. It is too stupid.
            delete array; // release memory of old array
            array = temp; // replace old array with new array
            max*=2;
        }
        int n;
        stream>>n;
        array[i++] = n;
    }
    // The number of integers in array is i. You can do anything with this number.
    delete array; // all done. clean up.
    return 0;
}

真正聪明的方法是使用std::vector。这很有可能会被标记所反对,所以创建自己的可调整大小的数组类。有了一个类,你可以很容易地利用RAII并自动化清理,因此它是异常安全的。