【问题标题】:Is it possible to use a character both as a double and a char?是否可以将一个字符同时用作双精度字符和字符?
【发布时间】:2017-06-16 10:31:12
【问题描述】:

我有一个像 ATGCCA... 这样的字符串。 该字符串将被转换为一个字符数组,如 [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=1 和 CCA=2” 嗯,请问?
  • n=atof(a);:这样不行。您必须使用字符串比较。相关功能可以在string.h 或者更好的cstring 中找到。一般来说,我建议使用std::string 而不是char*char[]std::string 提供查找或比较(子)字符串的方法。
  • 如果a=ATG,为什么n=atof(a)给你1?
  • 您能提供一个(不要太长)示例输入文件吗?我在在线编译器中尝试了其中一个答案的代码,但很难读取正确的数据。 (恐怕我的示例输入错误。否则,您的示例中的输入数据读取不正确。)(请使用 edit 链接编辑问题。)

标签: c++


【解决方案1】:

变量 ATG 和 CCA 与您读入的任何字符没有关系

您可能希望将字符串与双打相关联,为此您需要Associative Container,例如std::map&lt;std::string, double&gt;.

#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;
    }
}

【讨论】:

  • 谢谢 Caleth,没错,我想将字符串与双打相关联。
【解决方案2】:

您似乎正在读取一个字符串,即"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;
}

请注意,您可能希望使用ints 而不是doubles。 并且可能进行一些检查以确保读取的序列实际上是密码子。

您可能需要/想要使用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

【讨论】:

  • 谢谢桑乔,真的很有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多