如何在C ++中写入2D数组?

时间:2022-10-18 20:56:50

I am having trouble using 2D arrays.

我在使用2D数组时遇到问题。

I am using an array of arrays of strings.

我正在使用一组字符串数组。

Each line of the input file contains two strings and each line needs to be one array.

输入文件的每一行包含两个字符串,每行必须是一个数组。

Below is my code and the text from codons.txt. My code has a few extra cout commands for debugging. When I run it, it does not display the second string.

下面是我的代码和codons.txt中的文本。我的代码有一些额外的cout命令用于调试。当我运行它时,它不会显示第二个字符串。

Here is my code:

这是我的代码:

#include <iostream>
#include <cstdlib>
#include <cctype>
#include <fstream>

using namespace std;

int main()
{
    const int CODONSLENGTH=64;
    string codons[CODONSLENGTH][2];
    ifstream infile;
    //void readRNACodonTable(string [][2]);

    //readRNACodonTable(codons);

    infile.open("codons.txt");
    if (!infile.is_open()){
        cout << "ERROR: Coudn't open input file.";
        exit(1);
    }

    for (int i=0; i < CODONSLENGTH && !infile.eof(); i++) {
        cout << "DEGUG: start iteration " << i << endl;
        infile >> codons[i][0] >> codons[i][1];
        cout << "DEBUG: " << codons[i][0] << " " << codons[i][2] <<
        endl;
    }
    infile.close();

    system("PAUSE");
    return 0;
}

Here is codons.txt:

这是codons.txt:

GCU A
GCC A
GCA A
GCG A
CGU R
CGC R
CGA R
CGG R
AGA R
AGG R
AAU N
AAC N
GAU D
GAC D
UGU C
UGC C
CAA Q
CAG Q
GAA E
GAG E
GGU G
GGC G
GGA G
GGG G
CAU H
CAC H
AUU I
AUC I
AUA I
UUA L
UUG L
CUU L
CUC L
CUA L
CUG L
AAA K
AAG K
AUG M
UUU F
UUC F
CCU P
CCC P
CCA P
CCG P
UCU S
UCC S
UCA S
UCG S
AGU S
AGC S
ACU T
ACC T
ACA T
ACG T
UGG W
UAU Y
UAC Y
GUU V
GUC V
GUA V
GUG V

2 个解决方案

#1


There is a typo in your debug output, the subscript of the second string is 2 but it should be 1 (as indices start from 0, the second object is indexed at 1, like you did in the reading line).

调试输出中有一个拼写错误,第二个字符串的下标是2,但它应该是1(因为索引从0开始,第二个对象的索引为1,就像你在读取行中所做的那样)。

for (int i=0; i < CODONSLENGTH && !infile.eof(); i++) {
    cout << "DEGUG: start iteration " << i << endl;
    infile >> codons[i][0] >> codons[i][1];
    cout << "DEBUG: " << codons[i][0] << " " << codons[i][1] << endl; // <-- HERE
}

#2


You're writing to codons[i][1] but reading from codons[i][2].

你正在写密码子[i] [1]但是从密码子[i] [2]读书。

#1


There is a typo in your debug output, the subscript of the second string is 2 but it should be 1 (as indices start from 0, the second object is indexed at 1, like you did in the reading line).

调试输出中有一个拼写错误,第二个字符串的下标是2,但它应该是1(因为索引从0开始,第二个对象的索引为1,就像你在读取行中所做的那样)。

for (int i=0; i < CODONSLENGTH && !infile.eof(); i++) {
    cout << "DEGUG: start iteration " << i << endl;
    infile >> codons[i][0] >> codons[i][1];
    cout << "DEBUG: " << codons[i][0] << " " << codons[i][1] << endl; // <-- HERE
}

#2


You're writing to codons[i][1] but reading from codons[i][2].

你正在写密码子[i] [1]但是从密码子[i] [2]读书。