Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

read a file of a secret message, of unknown length, encoded in file something .d

ID: 3532898 • Letter: R

Question

read a file of a secret message, of unknown length, encoded in file something.dat to be decoded. The setup is simple: each line of the file contains one char and one nonnegative integer. The key to reading the message is organizing the characters in the proper order. The integer indicates the position of the character within the message. For example:

e 2

b 1

a 3 spells 'beach' when decoded

h 5

c 4

In C++, using a linked list, write a program that will:

1) ask the user for the name of a file, opening and reading this file exactly once,

2) unravel and display the message

3) offer to do it again on another file

Explanation / Answer

#include <iostream>

#include <string>


typedef struct LLIST{

int pos;

char c;

struct LLIST* next;

}list;


list* l = NULL;


int main()

{

string fn;

FILE* fp;

char ch;

int pos,flag;

list* node,*temp;

while(1)

{

printf("Enter file name ");

scanf("%s",fn);

fp = fopen(fn,"r");

while(fscanf("%c",&ch) != EOF)

{

fscanf("%d",&pos);

if(l == NULL)

{

node = (list*)malloc(sizeof(list));

node->c = ch;

node->pos = pos;

node->next = NULL;

l=node;

}

else

{

flag = 0;

temp = l;

while(l->pos < pos)

{

if(l->next == NULL)

{

node = (list*)malloc(sizeof(list));

node->c = ch;

node->pos = pos;

node->next = NULL;

l->next=node;

flag = 1;

}

else

l= l->next;

}

if(flag == 0)

{

node = (list*)malloc(sizeof(list));

node->c = ch;

node->pos = pos;

node->next = l->next;

l->next=node;

}

l=temp;

}

}

}

while(l!=NULL)

{

printf("%c",l->c);

l=l->next;

}

printf(" ");

}