2013-04-09 115 views
2

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

#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 
+2

的輸出是什麼,是節目結束芯片成功或失敗? – 2013-04-09 16:16:20

+0

使用'std :: vector'。沒有必要在這裏使用固定數組,只會使事情更加複雜。 – 2013-04-09 16:21:46

+0

「但它不會成功讀取」不是非常具體。請解釋錯誤/問題/意外輸出/等。你得到。 – 2013-04-09 16:24:29

回答

0

我不喜歡的東西你想使用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,因爲矢量通常更容易處理,在這種情況下沒有理由不這樣做。

0

如果每行包含一個字符,那麼這意味着你也讀取結束行字符(「\ n」)到DNA陣列。在這種情況下,你可以這樣做:

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

我懷疑這裏的問題不在於C++代碼,而在於文件位置。在Xcode中,二進制程序內置在可執行文件的位置。您必須設置構建階段才能將輸入文件複製到可執行文件位置。看到這個Apple Documentation