C ++ - 如何输入空间分隔的数字到数组? [英] C++ - How to input space separated numbers into array?

查看:110
本文介绍了C ++ - 如何输入空间分隔的数字到数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个文件:

4
10 3 4 6

第一行声明第二行has.I希望把在array.So第二行的数目多少个号码为止,我一直在使用这个循环自动申报第二行有多少个号码多少次做循环:

The first line declares how many numbers the second line has.I want to put the numbers of the second line in an array.So far i have been using this loop to automatically declare how many numbers the second line has and how many times to do the loop:

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

using namespace std;

int main(){
    ifstream infile;
    infile.open("input.in");
    string kids;
    int x;
    int i;
    getline(infile,kids);
    cout << "The Number Of Kids Is " << kids << endl;
    istringstream buffer(kids);
    int kidss;
    buffer >> kidss;
    for(i=0;i<kidss;i++){
        infile >> x;
        cout << x << " ";
    }
    infile.close();
    return 0;
}

现在我想要做同样的事情,但不是以x输入查询号码我希望把它们放入数组,然后显示它们作为above.Thanks在前进!

Now i want to do the same thing but instead of inputing the numbers in x i want to put them in an array and then display them as above.Thanks In Advance!

推荐答案

这样做的最好的办法就是用的 的std ::矢量 这些++在C变长数组。

The best way of doing this would be with a std::vector these are variable length arrays in c++.

要在这种情况下使用它们,你会做

To use them in this case you would do

std::vector<int> array;
for( int i = 0 ; i < kidss ; ++i ) {
    infile >> x;
    array.push_back(x);
}

然后,如果你想打印出来再你就可以做到

Then if you wanted to print them out again you would be able to do

for( int i = 0 ; i < array.size() ; ++i ) {
    std::cout << array[i] << " ";
}

这篇关于C ++ - 如何输入空间分隔的数字到数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆