在Xcode中从c++程序中读取.txt文件

Read .txt files from C++ program in Xcode

本文关键字:读取 txt 文件 程序 Xcode 中从 c++      更新时间:2023-10-16

我一直在努力让我的c++程序从Xcode读取我的。txt文件。我甚至试着把。txt文件放在我的Xcode c++程序的同一目录下,但它不会从它成功读取。我试图用文件中的所有核苷酸填充dna数组,所以我只需要读取一次,然后我就可以对该数组进行操作。下面只是我处理文件的一部分代码。整个程序的思想是编写一个程序,读取包含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中,二进制程序构建在可执行文件的位置。您必须设置构建阶段以将输入文件复制到可执行文件位置。参见Apple文档

如果每行包含一个字符,那么这意味着您也正在将行尾字符('n')读取到DNA数组中。在本例中,您可以这样做:

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

我做了一些事情,就像你最近尝试使用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);
    }
}

上面的操作读取存储在文件每行中的名称,并将它们添加到vector的末尾。因此,如果我的文件有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,因为vector通常更容易处理,在这种情况下没有理由不使用。