-2

我对 C++ 编程很陌生,我想展示

如何显示产生这种格式的 output.txt 文件。

ABCDEFGHIJKLMNOPQRSTU VWX YZ

TWGXZRLLNHAIAFLEWGQHV RNVDU

在文本文件中,但我不确定为什么它们显示为垃圾。

#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))<<" ";
        }



}
4

1 回答 1

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))<<" ";
        }
}
于 2012-07-17T16:30:51.190 回答