[英]Customer Decipher program c++ Trouble reading in
所以我有一個自定義解密程序,它讀入一個輸入文件並根據輸入的密鑰對其進行解密。 文本文件:
23
11
Java 2 linux 3 fear 0 pool 2 do 0 red 1 lock. 1 I 0 random 2 computers, 0 not 0 the 0 open 2 car! 2 C, 0 lack 0 of 0 dog 1 green 2 C++ 0 bottle 2 wrong, 2 them. 0
5 1 10 21 9 6 21 11 13 16 20
該文件表示為:
[Number of Words]
[Number of Keys]
[Word] [Jump] [Word] [Jump] ... [Word] [Jump]
[Key] [Key] ... [Key]
我設法讓程序讀入了鍵的數量和字數,但是我在讀入單詞和它們旁邊的數字以及最后一個數字並將它們注冊為鍵時遇到了麻煩。 這是我到目前為止:
#include <iostream>
#include <fstream>
using namespace std;
struct pieces {
char word;
int jump;
} ;
// Main Function
int main ()
{
// declare variables
int keyCount = 1;
int wordCount = 8;
int wordAmount[8];
int keyAmount[8];
pieces cipher[5];
char decoded[20][20];
char filename[10];
int keys[keyCount];
char tArray[20][20];
ifstream inData;
//prompt user for input file
cout << " Enter file name: ";
cin >> filename;
inData.open(filename);
if(inData.is_open());
{
// read list of names into array
for ( int i = 0; i < keyCount; ++i){
inData >> wordAmount[i] >> keyAmount[i];
for(int j = 0; j < wordCount; j++){
inData >> cipher[j].word >> cipher[j].jump;
}
}
cout << " Key Count: " << keyCount << "\n";
// print out
for ( int i = 0; i < keyCount; ++i){
cout << " KeyAmount: ";
cout << keyAmount[i] << "\n";
cout << " WordAmount: ";
cout << wordAmount[i] << "\n";
for(int j = 0; j < wordCount; j++){
cout << cipher[j].word << " " << cipher[j].jump;
}
}
}
inData.close();
return 0;
}
我確實嘗試將字符詞作為數組,但后來我得到了一個分段文件。 任何意見,將不勝感激!
恕我直言,如果您使用std::string
並重載格式化的輸入運算符>>
,您的項目會更簡單:
struct Word_Jump
{
std::string word; // Using std::string because it has space for more than one character.
int jump;
friend std::istream& operator>>(std::istream& input, Word_Jump& wj);
};
std::istream&
operator>>(std::istream& input, Word_Jump& wj)
{
input >> wj.word;
input >> jump;
return input;
}
您的輸入可能如下所示:
std::vector<Word_Jump> database;
for (unsigned int i = 0; i < number_of_words; ++i)
{
Word_Jump wj;
my_data_file >> wj;
database.push_back(wj);
}
同樣,您輸入以讀取密鑰:
std::vector<int> key_database;
for (unsigned int j = 0; j < number_of_keys; ++j)
{
int k = 0;
my_data_file >> k;
key_database.push_back(k);
}
所以以上是兩種可能的讀取單詞和跳轉對以及鍵的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.