【问题标题】:randomize char output to text file随机聊天输出到文本文件
【发布时间】:2012-07-17 16:18:10
【问题描述】:

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

如何显示产生这种格式的 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 YZ

T W G X Z R L L N H A I A F L E W G Q H V R N V D U

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

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



}

【问题讨论】:

  • 如何显示产生这种格式的 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
  • 不,不是凯撒密码。第一行应该是明文,第二行应该是26个字符,随机选择替换。
  • 如果我下面的回答有帮助,请标记它,让其他人知道问题已解决。
  • 顺便说一句,您似乎假设 'Z' == 'A' - 1 + 26。这不能保证,而且今天有一些运行 C++ 的机器不正确。

标签: c++ out


【解决方案1】:
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))<<" ";
        }
}

【讨论】:

  • 第二个代码sn-p不能保证每个字符都出现一次。
  • 但这不是必须的。查看示例 - A 是两倍。
  • 第二行之后也需要一个 \n 。我也更喜欢使用' ''\n' 输出单个字符,而不是输出字符串。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多