我有一個字符串像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
謝謝你的幫助!
_「我已經知道了ATG = 1和CCA = 2「_嗯,請問什麼? –
'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
如果a ='ATG',爲什麼'n = atof(a)'會給你1? – Walter