是否可以将字符同时用作替身和字符
Is it possible to use a character both as a double and a char?
我有一个像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* 作为键
相关文章:
- C++字符*缓冲区的大小
- HEX值到wchar_t字符(UTF-8)的转换
- 为什么 Serial.println(<char[]>);返回随机字符?
- 我的字符计数代码计算错误.为什么
- 字符串-C++后显示的随机字符
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 如何在C++中从字符串中分割字符
- 为什么msgrcv()将垃圾字符馈送到缓冲区
- 指向指向字符数组的指针数组的指针
- 如何用转义符替换字符串中的所有特殊字符
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 比较字符数组
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 是否可以将字符同时用作替身和字符
- C++ - 从 cin 中读一个替身,然后是一个字符