2012-07-17 67 views
-1

我很新的C++編程,我想顯示隨機化字符輸出到文本文件

如何以這種格式顯示產生output.txt文件。

A B C d E F G H I J K L M N 2 O P Qř式T U V W X arrow-

T W&ģX Z R L L N H A我A F L E W^g^Q H V RÑV dù

在文本文件

,但我不知道爲什麼它們顯示爲垃圾。

#include <iostream> 
#include <cstdlib> 
#include <ctime> 
#include <fstream> 
using namespace std; 


void random (std::ostream& output) 
{ 
    int letter[26]; 
    int i,j,temp; 

    srand(time(NULL)); 


     for(i=0; i<26; i++) 
      { 
       letter[i] = i+1; 
       output<<(char)(letter[i]+'A'-1)<<" "; 
//by ending endl here i am able to display but the letter will display in horizontal which is not what i wanted  

      }  

     for(i=0; i<26; i++) 
     { 
      j=(rand()%25)+1; 
      temp = letter[i]; 
      letter[i] = letter[j]; 
      letter[j] = temp; 
      output<<((char) (letter[i]+'A'-1))<<" "; 
     } 



} 
+2

你的問題是什麼? – jeschafe 2012-07-17 16:23:12

+0

如何以此格式顯示生成output.txt文件。 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z – newbieprogrammer 2012-07-17 16:26:23

+0

所以你想寫一個愚蠢的凱撒密碼?耶穌,那很難理解。 – akappa 2012-07-17 16:35:00

回答

0
void random (std::ostream& output) 
{ 
    int letter[26]; 
    int i,j,temp; 

    srand(time(NULL)); 


     for(i=0; i<26; i++) 
     { 
      letter[i] = i+1; 
      output<<(char)(letter[i]+'A'-1)<<" ";  

     }  
     output << "\n";  //that's all what you need 
     for(i=0; i<26; i++) 
     { 
      j=(rand()%25)+1; 
      temp = letter[i]; 
      letter[i] = letter[j]; 
      letter[j] = temp; 
      output<<((char) (letter[i]+'A'-1))<<" "; 
     } 



} 

未來 - 不使用std :: ENDL,因爲它也刷新流緩衝區,這可能是不必要的。改用'\ n'。但整個功能可以更簡單:

void random (std::ostream& output) 
{ 
    srand(time(NULL)); 


     for(int i = 65; i < 91; ++i)   // i == 65, because it's A in ASCII 
      output << (char)i << " "; 
     output << "\n";  //that's all what you need 

     for(int i=0; i<26; i++) 
     { 
      output <<((char)(rand()%26 + 65))<<" "; 
     } 
} 
+0

\ n做什麼? 這是不是在我的課上學習嘿嘿 – newbieprogrammer 2012-07-17 16:34:04

+0

\ n是一個新行的標誌 – Blood 2012-07-17 16:34:44

+0

第二個代碼片段不能確保每個字符只出現一次。 – timrau 2012-07-17 23:15:19