1

有一个文本文件。我需要取出第一个数字并将其他数字放入数组中。文件大小未知。在我的代码中,我首先尝试使用vector.size它来计算它的大小,然后构建数组。希望有人可以帮助我看看有什么问题。

示例输入文件:

3                   
2 2                   
output        
Can take out a=3;          
array[0]=2;array[1]=2;

代码:

int main()
{
    int n, inInt;
    vector <int> list;
    ifstream ifs("1.txt");

    int a;
    ifs>>a;
    std::vector<int> result;
    int temp;

    while(! ifs.eof())
    {
        ifs >> temp;
        result.push_back(temp);
    }

    int b;
    b=result.size();
    int numlist[b];

    for (int i=0;i<b;i++)
    {
        ifs>>numlist[i];
    } 
    cout<<numlist[0];

    ifs.close();
    system("pause");
    return 0;
}
4

2 回答 2

0
int main(int argc, char* argv[])
{
    int n, inInt;
    vector <int> list;
    ifstream ifs("1.txt");
    int a;
    ifs>>a;
    std::vector<int> result;
    int temp;
    while(! ifs.eof())
    {
        ifs >> temp;
        if(ifs.good())     //Check to see did the operation work
        result.push_back(temp);
    }
    int b;
    b=result.size();
    cout<<result[0];

    ifs.close();
    system("pause");
    return 0;
}
于 2013-07-21T09:52:51.450 回答
0

首先,如果你想创建一个你不知道你必须使用的大小的数组:

int *numlist = new int[b];

并在您的代码末尾:

delete[] numlist;

其次,当你有一个保存文件值的向量时,再次读取文件有什么意义?这样做会不会更容易:

for (i=0; i < b; i++)
     numlist[i] = result[i];

我希望这可以帮助你。

于 2013-07-21T10:03:33.700 回答