簡體   English   中英

從文件中讀取數據並將每行存儲在數組中?

[英]Reading data from a file and storing each line in an array?

我有一個整數行的文件。 我想將每一行讀入我的數組中的一個插槽。 我有下面的代碼,但它不起作用。 我不確定我是否走在正確的軌道上。

void Read_Save() {
    ifstream in;
    int arr[100];
    string line;
    in.open("file.txt");
    while (in.peek() != EOF)
    {
        getline(in, line, '\n');
        strcpy(arr, line.c_str());
    }
    in.clear(); in.close();
}

有幾種方法可以解析字符串中的整數值。

首先,讓我們修復你的循環:

int pos = 0;
while( std::getline(in, line) && pos < 100 )
{
    int value = 0;

    // Insert chosen parsing method here

    arr[pos++] = value;
}

以下是常見選項的非詳盡列表:

  1. 使用std::strtol

     // Will return 0 on error (indistinguishable from parsing actual 0) value = std::strtol( line.c_str(), nullptr, 10 ); 
  2. 使用std::stoi

     // Will throw exception on error value = std::stoi( line ); 
  3. 構建一個std::istringstream並從中讀取:

     std::istringstream iss( line ); iss >> value; if( !iss ) { // Failed to parse value. } 
  4. 使用std::sscanf

     if( 1 != std::sscanf( line.c_str(), "%d", &value ) ) { // Failed to parse value. } 

現在,注意循環檢查pos < 100的邊界測試。 這是因為您的陣列具有存儲限制。 實際上,你還使用Read_Save的本地數據覆蓋了全局的Read_Save ,從而將它隱藏在一個較小的數組中,該數組在函數完成時將丟失。

您可以使用標准庫提供的其他容器類型來擁有任意大小的“數組”(實際上不是數組)。 提供隨機訪問的有用的是std::vectorstd::deque 讓我們使用向量並將Read_Save的定義更改為更有用:

std::vector<int> Read_Save( std::istream & in )
{
    std::vector<int> values;
    std::string line;

    for( int line_number = 1; getline( in, line ); line_number++ )
    {
        try {
            int value = std::stoi( line );
            values.push_back( value );
        }
        catch( std::bad_alloc & e )
        {
            std::cerr << "Error (line " << line_number << "): Out of memory!" << std::endl;
            throw e;
        }
        catch( std::exception & e)
        {
            std::cerr << "Error (line " << line_number << "): " << e.what() << std::endl;
        }
    }

    return values;
}

最后,電話變為:

std::ifstream in( "file.txt" );
std::vector<int> values = Read_Save( in );

您不能使用strcpy()將字符串轉換為整數。 你可以使用std::strtol()std::stoi() ,甚至是std::istringstream ,例如:

int arr[1000];

void Read_Save() {
    ifstream in;
    string line;
    in.open("file.txt");
    int index = 0;
    while ((index < 1000) && (getline(in, line)))
    {
        if (istringstream(line) >> arr[index])
            ++index;
    }
}

在你的情況下,最好的辦法是使用std::vector 代碼如下所示:

void Read_Save()
{
    std::ifstream in("file.txt");
    int value;
    std::vector<int> arr;

    while (in >> value)
        arr.push_back(value);

    for(int i(0); i < arr.size(); i++)
        std::cout << arr[i] << ", ";

    std::cout << std::endl;
    in.close();
}

暫無
暫無

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

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