having trouble understanding IO directory and pipe line command - c++11

im trying to encrypt the f1.txt file by shifting the letter based off the number and write it to f2.txt. but im not sure if the contents of f1.txt go into ./cf
$ cat f1.txt | ./cf -e 3 > f2.txt
int main(int argc, char ** argv){
char alpha[26] = {'A','B','C','D','E','F','G','H','I','J','K','L', // alphabet arr
'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
//ifstream input(argv[0]);
string line = "";
if(input.fail()){
cout << "error opening file "<<endl;
exit(1);
}
string type = argv[1];
if(type == "-e"){
while(getline(input,line)){
char plain [line.length()]; // array to store plain text
strcpy(plain, line.c_str()); //putting input into char array
string cipher_text = ""; // variable to store plain text
int shift = atoi(argv[2]);
for(int x = 0; x < line.length(); x++){ //for loop runs through char array
//and add plain letter based on shift
if((char(plain[x]) >= 65) && (char(plain[x]) <= 90)){;
cipher_text += cipher_letter(alpha,shift,string(1,plain[x]));
}else
cipher_text += plain[x];
}
cout << cipher_text << endl;
}
}else if(type == "-d"){
while(getline(input,line)){
char cipher [line.length()]; // array to store plain text
strcpy(cipher, line.c_str()); //putting input into char array
string plain_text = ""; // variable to store plain text
int shift = atoi(argv[2]);
for(int x = 0; x < line.length(); x++){ //for loop runs through char array
//and add plain letter based on shift
if((char(cipher[x]) >= 65) && (char(cipher[x]) <= 90)){
plain_text += plain_letter(alpha,-shift,string(1,cipher[x]));
}else
plain_text += cipher[x];
}
cout<< plain_text << endl;
}
}
input.close();
}

Related

How to repeat tensor in libtorch

I am using libtorch to inference, I have read data from txt file to vector and convert to tensor, I want to repeat a tensor three times then change it to 3D,
I tried this
std::vector<std::vector<float>> feature_data(255, std::vector<float>(221));
ifstream f_data("../data.txt"); //
if (! f_data) {
cout << "Error, file couldn't be opened" << endl;
return 1;
}
for(int i=0;i<255;i++)
{
for(int j=0;j<221;j++)
{
if ( !f_data )
{
std::cout << "read error" << std::endl;
break;
}
f_data >> feature_data[i][j];
}
}
auto data_options = torch::TensorOptions().dtype(at::kFloat);
auto feature_tensor = torch::zeros({255,221}, data_options);
for (int i = 0; i < 255; i++)
feature_tensor.slice(0, i,i+1) = torch::from_blob(feature_data[i].data(), {221},
data_options);
// begin to repeat three times
auto tensor_clone = feature_tensor.clone();
auto one_time_clone = torch::cat({feature_tensor, tensor_clone}, 0);
auto two_times_clone = torch::cat({one_time_clone, tensor_clone}, 0);
auto transformed_asr = two_times_clone.view({3, 255, 221});
it looks troublesome and I am not sure if it is right, is there an easy way?
...
for (int i = 0; i < 255; i++)
feature_tensor.slice(0, i,i+1) = torch::from_blob(feature_data[i].data(), {221},
data_options);
auto tensor_clone = feature_tensor.repeat({3, 1});
...

Why is my code allocating an unnecessary amount of bytes from my w10_text.dat file? (OOP345 SENECA)

void SecureData::backup(const char* file) {
if (!text)
throw std::string("\n***No data stored***\n");
else if (!encoded)
throw std::string("\n***Data is not encoded***\n");
else {
// open binary file
std::ofstream is;
is.open(file, std::ios::out);
// write binary file here
if (is.fail())
{
throw std::string("\n***No file could be opened " + std::string(file) + " ***\n");
}
else
{
for (int i = 0; i < nbytes; i++)
{
is << text[i];
}
}
}
}
void SecureData::restore(const char* file, char key) {
// open binary file
std::ifstream os;
os.open(file, std::ios::in);
if (os.fail())
{
throw std::string("\n***No file could be opened " + std::string(file) + " ***\n");
}
else
{
nbytes = 0;
char tempchar = 0;
while (os.good())
{
os >> tempchar;
nbytes++; //!< count number of chars
}
std::cerr << nbytes << std::endl;
text = new char[nbytes]; //!< allocate memory here
os.clear();
os.seekg(0, std::ios::beg);
for (int i = 0; i < nbytes; i++)
{
os >> text[i]; //!< read binary file here
}
}
std::cout << "\n" << nbytes + 1 << " bytes copied from binary file "
<< file << " into memory (null byte included)\n";
encoded = true;
// decode using key
code(key);[enter image description here][1]
std::cout << "Data decrypted in memory\n\n";
}
I believe the error lies in my backup(const char * file) however I do not know where the issue is. I would really appreciate feed back and a second pair of eyes. Cheers!
As this is for a class I also included the lab link that I am completing, as well as a image of my output bellow:
https://scs.senecac.on.ca/~oop345/pages/workshops/w10.html
os.read(text, nbytes);
Replaced the for look with the code above worked. I assume the ">>" operators was the issue.
for (int i = 0; i < nbytes; i++)
{
os >> text[i]; //! read binary file here
};

Parsing through Vectors

I am new and learning C++ using the Programming Principles ... book by Bjarne Stroustrup. I am working on one problem and can't figure out how to make my code work. I know the issue is with if (words[i]==bad[0, bad.size() - 1]) in particular bad.size() - 1])
I am trying to out put all words in the words vector except display a bleep instead of any words from the words vector that match any of the words in the bad vector. So I need to know if words[i] matches any of the values in the bad vector.
#include "../std_lib_facilities.h"
using namespace std;
int main()
{
vector<string> words; //declare Vector
vector<string> bad = {"idiot", "stupid"};
//Read words into Vector
for(string temp; cin >> temp;)
words.push_back(temp);
cout << "Number of words currently entered "
<< words.size() << '\n';
//sort the words
sort(words);
//read out words
for(int i = 0; i < words.size(); ++i)
if (i==0 || words[i-1]!= words[i])
if (words[i]==bad[0, bad.size() - 1])
cout << "Bleep!\n";
else
cout << words[i] << '\n';
return 0;
}
You need to go through all of the entries in the bad vector for each entry in the words vector. Something like this:
for(const string& word : words)
{
bool foundBadWord = false;
for(const string& badWord : bad)
{
if(0 == word.compare(badWord))
{
foundBadWord = true;
break;
}
}
if(foundBadWord)
{
cout << "Bleep!\n";
}
else
{
cout << word << "\n";
}
}

custom ITOA not working right?

I wanted to make a custom ITOA function to put large numbers into small strings, this is what I have coded :
main(){
printf("itoa(2000000000,36)= '%s'",itoa(2000000000,36));
printf("itoa(36,36)= '%s'",itoa(36,36));
printf("itoa(37,36)= '%s'",itoa(37,36));
return 1;
}
stock itoa(val, base)
{
new buf[1024] = {0,...};
new i = 1023;
new LETTERZ[37] = {'0','1','2','3','4','5','6','7','8','9','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',0};
for(; val && i; --i, val /= base)
buf[i] = LETTERZ[val % base];
return buf[i+1];
}
It's based on 'C' code from this page: http://www.jb.man.ac.uk/~slowe/cpp/itoa.html
But somehow this is the output:
[20:34:35] itoa(2000000000,36)= 'X'
[20:34:35] itoa(36,36)= '1'
[20:34:35] itoa(37,36)= '1'
And this is totally wrong, I don't know which output to expect but 36 and 37 for sure can't be the same output and 2 000 000 000 can't be just 'X', as X is suposed to be 35, not 2 000 000 000,
ZZ should be 1295 I think... I want to base this on the hexadecimal system, but with all the alfabet letters.
Could anyone tell me what's wrong here?
I'm working with a typeless language called PAWN (also known as SMALL) and later i want to use this code in VB.NET
/* itoa example */
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i;
char buffer [33];
printf ("Enter a number: ");
scanf ("%d",&i);
itoa (i,buffer,10);
printf ("decimal: %s\n",buffer);
itoa (i,buffer,16);
printf ("hexadecimal: %s\n",buffer);
itoa (i,buffer,2);
printf ("binary: %s\n",buffer);
return 0;
}
You only give the number and the base, but parameter 2 needs a pointer to char already allocated. Use a buffer or try NULL, so the function will return the result.
THe solution seemed to be simple, the return buf[i+1] just returned one character so what I did is make it return an array:
new _s#T[4096];
#define sprintf(%1) (format(_s#T, SPRINTF_MAX_STRING, %1), _s#T)
main(){
new num = atoi("ABCDEFG",36);
printf("%d",num);
printf("%s",itoa(num,36));
return 1;
}
stock itoa(val, base)
{
new buf[1024] = {0,...};
new LETTERZ[37] = {'0','1','2','3','4','5','6','7','8','9','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',0};
for(new pos = 0; val;++pos,val = floatround(val/base,floatround_floor))
strins(buf,sprintf("%c",LETTERZ[val % base]),0);
return buf;
}
stock atoi(val[], base)
{
new CURRNUM = 0;
new len = strlen(val);
new LETTERZ[37] = {'0','1','2','3','4','5','6','7','8','9','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',0};
for(new i = 0; i < len; ++i)
{
for(new x = 0; x < base; ++x)
{
new y = (len-i)-1;
if(val[y] == LETTERZ[x])
{
CURRNUM += x*floatround(floatpower(base,i));
}
}
}
return CURRNUM;
}

using sscanf(), read string to array of int?

i have this string:
12 4 the quick 99 -1 fox dog \
what i want in my program:
myArray[] = {12, 4, 99, -1};
how i do a multiple number scanning?
See my answer to your other question here. It's a relatively simple matter to replace the strtok section to recognize non-numeric words and neither increment the count (in the first pass) nor load them into the array (in the second pass).
The code has changed as follows:
Using an input file of:
12 3 45 6 7 8
3 5 6 7
7 0 -1 4 5
12 4 the quick 99 -1 fox dog \
it produces output along the lines of:
0x8e42170, size = 6:
12 3 45 6 7 8
0x8e421d0, size = 4:
3 5 6 7
0x8e421e0, size = 5:
7 0 -1 4 5
0x8e42278, size = 4:
12 4 99 -1
Here's the code that produced that output:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
// This is the linked list of integer arrays.
typedef struct _tIntArray {
int size;
int *array;
struct _tIntArray *next;
} tIntArray;
static tIntArray *first = NULL;
static tIntArray *last = NULL;
// Check that argument is numeric, optional minus sign followed by
// zero or more digits (you may want one or more).
static int isAllNumeric (char *word) {
char *s = word;
if (*s == '-')
s++;
for (; *s != '\0'; s++)
if ((*s < '0') || (*s > '9'))
return 0;
return 1;
}
// Add a line of integers as a node.
static int addNode (char *str) {
tIntArray *curr; // pointers for new integer array.
char *word; // word within string.
char *tmpStr; // temp copy of buffer.
int fldCnt; // field count for line.
int i;
// Count number of fields.
if ((tmpStr = strdup (str)) == NULL) {
printf ("Cannot allocate duplicate string (%d).\n", errno);
return 1;
}
fldCnt = 0;
for (word = strtok (tmpStr, " "); word; word = strtok (NULL, " "))
if (isAllNumeric (word))
fldCnt++;
free (tmpStr);
// Create new linked list node.
if ((curr = malloc (sizeof (tIntArray))) == NULL) {
printf ("Cannot allocate integer array node (%d).\n", errno);
return 1;
}
curr->size = fldCnt;
if ((curr->array = malloc (fldCnt * sizeof (int))) == NULL) {
printf ("Cannot allocate integer array (%d).\n", errno);
free (curr);
return 1;
}
curr->next = NULL;
for (i = 0, word = strtok (str, " "); word; word = strtok (NULL, " "))
if (isAllNumeric (word))
curr->array[i++] = atoi (word);
if (last == NULL)
first = last = curr;
else {
last->next = curr;
last = curr;
}
return 0;
}
int main(void) {
int lineSz; // current line size.
char *buff; // buffer to hold line.
FILE *fin; // input file handle.
long offset; // offset for re-allocating line buffer.
tIntArray *curr; // pointers for new integer array.
int i;
// Open file.
if ((fin = fopen ("qq.in", "r")) == NULL) {
printf ("Cannot open qq.in, errno = %d\n", errno);
return 1;
}
// Allocate initial line.
lineSz = 2;
if ((buff = malloc (lineSz+1)) == NULL) {
printf ("Cannot allocate initial memory, errno = %d.\n", errno);
return 1;
}
// Loop forever.
while (1) {
// Save offset in case we need to re-read.
offset = ftell (fin);
// Get line, exit if end of file.
if (fgets (buff, lineSz, fin) == NULL)
break;
// If no newline, assume buffer wasn't big enough.
if (buff[strlen(buff)-1] != '\n') {
// Get bigger buffer and seek back to line start and retry.
free (buff);
lineSz += 3;
if ((buff = malloc (lineSz+1)) == NULL) {
printf ("Cannot allocate extra memory, errno = %d.\n", errno);
return 1;
}
if (fseek (fin, offset, SEEK_SET) != 0) {
printf ("Cannot seek, errno = %d.\n", errno);
return 1;
}
continue;
}
// Remove newline and process.
buff[strlen(buff)-1] = '\0';
if (addNode (buff) != 0)
return 1;
}
// Dump table for debugging.
for (curr = first; curr != NULL; curr = curr->next) {
printf ("%p, size = %d:\n ", curr, curr->size);
for (i = 0; i < curr->size; i++)
printf (" %d", curr->array[i]);
printf ("\n");
}
// Free resources and exit.
free (buff);
fclose (fin);
return 0;
}

Resources