2012-07-17 45 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