Lab - Report9 2
Lab - Report9 2
Task 1:
Write a complete C++ program that scans 5 integers and 5 strings, stores them in the
structure “struct q2”, and prints them to the screen.
struct q2{
int age;
char name[20];
};
1.1 How would you declare an array of q2 objects to store 5 sets of integers and strings?
struct to define a composite data type containing an integer and a string
1.2 How would you read and store the integer age input by the user?
use the scanf() function
1.3 How would you read and store the string name input by the user?
use the scanf() function with the %s format specifier.
1.4 How would you handle any potential buffer overflow when reading the string name?
use fgets() instead of scanf(). Using fgets() allows you to specify the maximum number of
characters to read,
Task 2: Run the following code ready for string functions. Use one function at a time and
observe the output.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
char a[20]="computer", b[20]="prog";
int x;
printf("%s\t%s\n\n",a,b);
strcpy(a,b);
//strcpy(b,a);
//strncpy(a,b,2);
//strcat(a,b);
//strcat(b,a);
//strncat(a,b,3);
//x = strlen(a);
x = strcmp(b,a);
printf("\nx = %d\n",x);
printf("%s\t%s\n\n",a,b);
system("PAUSE");
return 0;
}
Task 3: Write a complete C/C++ program that gets an id and a string from the file
passwords.txt, then displays everything to the screen.
Passwords.txt:
1 asdpe%%2
2 jrpd&*
3 ………..
……………..
3.1 How does the program open the file? What mode is used? By fopen
3.2 How does the program read the content from the file? By fscanf
3.3 where should the “passwords.txt” file be located in order to access the file successfully?
file should be located at the specific absolute path specified in the code
Task 1
#include<iostream>
using namespace std;
struct q2{
int age;
char name[20];
};
int main(){
q2 data[5];
cout<<"Enter 5 Ages and 5 Names";
for(int i=0;i<5;i++){
cout<<"Age "<<i+1<<": ";
cin>>data[i].age;
cin.ignore();
cout<<"Name "<<i+1<< " :";
cin>>data[i].name;
}
cout<<" Displaying the contents " <<endl;
for(int i=0;i<5;i++){
cout<<i+1<<" : "<<endl;
display(data[i]);
}
return 0;
}
Task 3
#include<iostream>
using namespace std;
int main(){
FILE *file=fopen("password.txt", "r");
if(file==NULL){
printf("Failed to open the file. \n");
return 1;
int id;
char password[100];
fclose(file);
return 0;
}