繁体   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