簡體   English   中英

從Xcode中的C ++程序讀取.txt文件

[英]Read .txt files from C++ program in Xcode

我一直在努力讓我的C ++程序從Xcode讀取我的.txt文件。 我甚至嘗試將.txt文件放在我的Xcode C ++程序的同一目錄中,但它不會成功讀取它。 我試圖用文件中的所有核苷酸填充dnaData數組,所以我只需要讀一次然后我就可以對該數組進行操作。 下面只是處理文件的代碼的一部分。 整個程序的想法是編寫一個程序,讀取包含DNA序列的輸入文件(dna.txt),以各種方式分析輸入,並輸出包含各種結果的幾個文件。 輸入文件中的最大核苷酸數(見表1)為50,000。 有什么建議嗎?

#include <fstream>
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

const int MAX_DNA = 50000;

// Global DNA array. Once read from a file, it is
// stored here for any subsequent function to use
char dnaData[MAX_DNA];

int readFromDNAFile(string fileName)
{
int returnValue = 0;

ifstream inStream;
inStream.open(fileName.c_str());

    if (inStream.fail())
    {
        cout << "Input file opening failed.\n";
        exit(1);
    }

    if (inStream.good())
    {
        char nucleotide;
        int counter = 0;
        while ( inStream >> nucleotide )
        {
            dnaData[counter] = nucleotide;
            counter++;
        }
        returnValue = counter;
    }

    inStream.close();
    return returnValue;
    cout << "Read file completed" << endl;

} // end of readFromDNAfile function

我懷疑這里的問題不是C ++代碼,而是文件位置。 在Xcode中,二進制程序構建在Executables位置。 您必須設置構建階段以將輸入文件復制到Executables位置。 請參閱此Apple文檔

我做了類似你最近嘗試使用這樣的vector事情:

vector<string> v;
// Open the file
ifstream myfile("file.txt");
if(myfile.is_open()){
    string name;
    // Whilst there are lines left in the file
    while(getline(myfile, name)){
        // Add the name to the vector
        v.push_back(name);
    }
}

上面讀取存儲在文件每一行上的名稱,並將它們添加到向量的末尾。 因此,如果我的文件是5個名稱,將發生以下情況:

// Start of file
Name1    // Becomes added to index 0 in the vector
Name2    // Becomes added to index 1 in the vector
Name3    // Becomes added to index 2 in the vector
Name4    // Becomes added to index 3 in the vector
Name5    // Becomes added to index 4 in the vector
// End of file

試試看,看看它對你有用。

即使你沒有按照上面顯示的方式進行,我仍然建議使用std :: vector ,因為向量通常更容易使用,並且在這種情況下沒有理由不這樣做。

如果每行包含一個字符,那么這意味着您還在讀取DNA數組中的行尾字符('\\ n')。 在這種情況下,您可以這樣做:

while ( inStream >> nucleotide )
{
        if(nucleotide  == '\n')
        {
              continue;
        }
        dnaData[counter] = nucleotide;
        counter++;
}

暫無
暫無

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

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