是否可以将字符同时用作替身和字符

Is it possible to use a character both as a double and a char?

本文关键字:字符 替身 是否      更新时间:2023-10-16

我有一个像ATGCCA这样的字符串... .此字符串将转换为 char 数组,作为 [ATG CCA ...]。我已经知道 ATG=1 和 CCA=2,我将它们定义为双精度。如何将转换后的矩阵保存为双精度矩阵?这是我现在的程序,但它不起作用:

#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 和 CCA 与您读取的任何字符无关

您可能希望将字符串关联到双精度,为此您需要一个关联容器,例如 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;
    }
}

您似乎正在读取一个字符串,该字符串"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 s 而不是 double s。也许会进行一些检查,以确保读取的序列实际上是密码子。

您可能需要/想要对地图对的键使用 array,请参阅

无符号字符数组作为映射中的键 (STL - C++(

字符数组作为映射中的值C++

在 std::map 中使用 char* 作为键