在Xcode中从c++程序中读取.txt文件
Read .txt files from C++ program in Xcode
我一直在努力让我的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通常更容易处理,在这种情况下没有理由不使用。
相关文章:
- 一种在C++中读取TXT配置文件的简单方法
- 如何读取 TXT 文件并仅将 int 存储在 C 中
- 如何在C++中读取.txt文件
- 尝试读取.txt文件并根据用户输入的字母拉出特定行
- 读取.txt文件C++
- 如何在 c++ 中使用 fstream 读取.txt文件
- 如何用 c++ 读取 txt 文件,如果我们不知道其中有多少个数据字符串,以及每行有多长?
- 要读取txt文件并从第二列中找到其最小值的第一列值
- C 如何通过特定n字符读取TXT文件的值
- C :按行读取txt文件的读数,单词用单词读取,每行的单词不均匀
- 读取.txt文件并将每行放入向量
- 动态分配读取 txt 文件的内存
- 读取.txt文件并组织成二维数组
- 如何从现有目录中读取TXT文件
- 尝试创建一个读取.txt文件,显示它,计数唯一单词的程序,并在使用了多少次的情况下显示独特的单词.C
- 读取.txt文件中的多行并输出每行的答案
- 在生成器 6 中使用 ifstream 读取 txt 文件C++
- 内核模式:如何逐行读取 txt 文件
- c++读取txt文件并复制到两个类istream::peek()中
- C :使用ARGV [1]到一个函数中读取.txt文件的错误