簡體   English   中英

C ++動態數組和文件讀取不能一起使用

[英]C++ the dynamic array and file reading don't work together

這樣的代碼:

int _tmain(int argc, _TCHAR* argv[])
{
    int *test = new int[];
    ifstream f("ofile.txt");
    for (int i=0,v; i<10; i++)
    {
        f>>v;
        test[i]=1; 
        cout<<"\nv = "<<v<<", i = "<<i<<endl;
    }

    return 0;
}

導致此消息編譯后:

在此處輸入圖片說明

我猜(如果我錯了,請糾正我)這是有關內存的一些錯誤,但是細節對我來說是未知的。 如果我刪除其中之一(文件讀取或數組),則可以工作。 因此,很高興聽到對此問題的解釋。

您在考慮Java。 要分配這樣的數組,您需要提供一個大小。 例如

    int *test = new int[20];

但是,更好的方案是使用整數向量。

    #include <iostream>
    #include <fstream>
    #include <vector>
    #include <algorithm>  // for sort()

    int main(int argc, char *argv[])
    {
        std::vector<int> data;
        std::ifstream fsin("ofile.txt");

        int count = 0;
        while (fsin.good())
        {
            int v;
            fsin >> v;
            if (fsin.good())
            {
                data.push_back(v);
                std::cout << "\nv = " << v << ", i = " << count++ << std::endl;
            }
        }

        std::sort(data.begin(), data.end());

        for (size_t i=0; i<data.size(); i++)
            std::cout << i << '\t' << data[i] << std::endl;

        return 0;
    }

您必須分配一個固定大小的數組, int *test = new int[]; 甚至不應該工作。

如果已知大小,則使用int *test = new int[size]; ,否則請嘗試使用std::vectorstd:array

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM