2017-06-16 21 views
-3

我有一個字符串像ATGCCA ...。 該字符串將被轉換爲[ATG CCA ...]字符數組。 我已經知道ATG = 1和CCA = 2,並且我將它們定義爲double。如何將轉換後的矩陣保存爲雙精度型? 這裏是我的程序了,但它不工作:是否可以將字符同時用作double和char?

#include <iostream> 
#include <fstream> 
#include <string> 
#include <cstdlib> 
#include <cstdlib> 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <math.h> 

using namespace std; 

int main() { 
double ATG=1, CCA=2; 

fstream fp("sequence.txt",ios::in); 
if(!fp) 
{ 
    cerr<<"File can not open!"<<endl; 
    exit(1); 
} 

char content,k,l,m; 
char a[4]=""; 
double n; 

while(fp>>k>>l>>m){ 
fp.read(a, sizeof(a) - 1); 
    n=atof(a); 
    cout<<a<<" "<<n<<endl; 
} 
} 

我希望看到這樣的輸出:

ATG 1 
CCA 2 

但我看到的是:

ATG 0 
CCA 0 

謝謝你的幫助!

+1

_「我已經知道了ATG = 1和CCA = 2「_嗯,請問什麼? –

+0

'n = atof(a);':它不能這樣工作。你必須使用字符串比較。相關的函數可以在'string.h'或更好的['cstring'](http://en.cppreference.com/w/cpp/header/cstring)中找到。一般來說,我會建議使用['std :: string'](http://en.cppreference.com/w/cpp/string/basic_string)而不是'char *'或'char []'。 'std :: string'提供了查找或比較(子)字符串的方法。 – Scheff

+0

如果a ='ATG',爲什麼'n = atof(a)'會給你1? – Walter

回答

1

好像你正在閱讀的字符串,這是"ATG",並且你希望atof使用,作爲一個變量,從中提取其值的名稱。在這個推理中有幾個鏈式的恐怖分子。

你會需要像一個map(代碼未測試):

#include <map> 
#include <string> 
#include <iostream> 
#include <fstream> 

using namespace std; 

int main() { 
    map<string, double> amino; 
    amino["ATG"] = 1; 
    amino["CCA"] = 2; 
    // ... Complete with the other 62 codons 

    fstream fp("sequence.txt",ios::in); 
    if(!fp) 
    { 
     cerr<<"File can not open!"<<endl; 
     exit(1); 
    } 

    char content, k, l, m; 
    char a[4]=""; 
    double n; 

    while(fp >> k >> l >> m) { 
    fp.read(a, sizeof(a) - 1); 
     n = amino[a]; 
     cout << a << " " << n << endl; 
    } 

    return 0; 
} 

請注意,您可能需要使用int!而非double秒。 也許一些檢查,以確保讀取的序列實際上是密碼子。

您可能需要/想使用array爲圖對鑰匙,看到

unsigned char array as key in a map (STL - C++)

Character Array as a value in C++ map

Using char* as a key in std::map

+0

謝謝桑喬, 這真的很有幫助。 –

4

變量ATG和CCA有沒有關係您在讀取任何字符。

你可能想字符串雙打,而您將需要一個Associative Container,例如關聯std::map<std::string, double>

#include <iostream> 
#include <fstream> 
#include <string> 

int main() { 
    std::map<std::string, double> lookup = { { "ATG", 1}, { "CCA", 2 } }; 

    std::fstream fp("sequence.txt",std::ios::in); 
    if(!fp) 
    { 
     std::cerr<<"File can not open!"<<std::endl; 
     exit(1); 
    } 

    char content,k,l,m; 
    char a[4]=""; 
    double n; 

    while(fp>>k>>l>>m){ 
    fp.read(a, sizeof(a) - 1); 
     n=lookup[a]; 
     std::cout<<a<<" "<<n<<std::endl; 
    } 
} 
+0

謝謝Caleth, 是的,我想把字符串聯繫到雙打。 –

相關問題