2015-02-07 123 views
-2

我想寫一個程序轉錄DNA到RNA,我不能弄清楚如何讓程序輸出一個字符串。我知道它涉及到聲明一個字符串並在for循環中使用它。到目前爲止,我已經輸出的程序只輸出單個變量的正確答案。這是我做的遠:for循環中的C++字符串

#include <iostream> 
using namespace std; 

int main() 
{ 
    cout << "> "; 
    cin >> dna; 
    string dna; 
    cout "< "; 
     if (a == 'A') cout << 'U'; 
    else if (a == 'C') cout << 'G'; 
    else if (a == 'G') cout << 'C'; 
    else if (a == 'T') cout << 'A'; 
    cout << " " << endl; 
} 
+1

其中是變量a的聲明? (dna =='A'),你的意思是? – 2015-02-07 19:02:28

+0

預期產量是多少?附:您可能需要考慮縮進代碼並在if語句後使用花括號{} – 121c 2015-02-07 19:02:52

+0

爲什麼不先讓代碼編譯? – 2015-02-07 19:03:32

回答

0

您可以簡單地使用此代碼。注意你的程序有幾個錯誤,嘗試一步一步地修復它們,比如首先需要在使用它之前聲明一個變量或者需要編寫聲明cout < <「<」; cout「<」;

#include <iostream> 
using namespace std; 

int main() 
{ 
    string dna; 
    char a; 
    cout << "> "; 
    cin >> dna; 

    cout << "< "; 
    for(int i=0 ; i<dna.size() ;i++){ 

     a = dna[i]; 
     if (a == 'A') cout << 'U'; 
     else if (a == 'C') cout << 'G'; 
     else if (a == 'G') cout << 'C'; 
     else if (a == 'T') cout << 'A'; 
    } 
    cout << " " << endl; 
} 
1
#include <iostream> 
#include <string> 

int main() { 
    std::string dna; 
    std::cout << "Type a DNA String\n> "; 
    std::cin >> dna; 
    std::cin.ignore(); 
    std::cout << "< "; 
    int i = 0; 
    for (; i < dna.size()`enter code here`; i++) { 
     if (dna[i] == 'A') { 
     std::cout << "U"; 
     } 
     else if (dna[i] == 'T') { 
     std::cout << "A"; 
     } 
     else if (dna[i] == 'C') { 
     std::cout << "G"; 
     } 
     else if (dna[i] == 'G') { 
     std::cout << "C"; 
     } 
     else return 1; 
    } 
    return 0; 
} 

它要求輸入的字符串,然後循環,並通過條件決定了輸出。

事情來看待:

  1. 申報之前定義
  2. 不要拿整個字符串
  3. 超前思考和設置錯誤處理。
+0

我認爲這是我需要的。如果你使用namespace std添加;在開始時你可以避免不得不一遍又一遍地重寫它? – Tyler 2015-02-07 19:30:53

+0

@Tyler最好避免使用namespace std;至少在頭文件中。這些將暴露您的代碼容易出現命名空間衝突。 – 2015-02-07 19:32:39

+0

是的,但如果你真的想,那麼你可以刪除我看到的每一個'std ::' – 2015-02-07 19:33:11

1

您的代碼doesn't compile。你大概的意思是寫這樣的事情

#include <iostream> 
#include <string> 

using namespace std; 

int main() { 
    cout << "> "; 
    string dna; // << put the declaration 1st 
    cin >> dna; 
    cout << "< "; 
    for(auto a : dna) { 
     switch(a) { 
     case 'A': cout << 'U'; 
      break; 
     case 'C': cout << 'G'; 
      break; 
     case 'G': cout << 'C'; 
      break; 
     case 'T': cout << 'A'; 
      break; 
     } 
    }   
    cout << " " << endl; 
    return 0; 
} 

Here's the completely fixed and running version.

+0

爲什麼要比較整個字符串?你需要數組訪問,單引號在一定程度上是正確的。 – 2015-02-07 19:13:27

+0

@Isaiah我沒有關注語義,OP對此並不清楚。我剛剛解決了顯而易見的問題。 – 2015-02-07 19:16:55

+0

爲什麼不發表評論?現在我無法撤銷我的投票... – 2015-02-07 19:20:31