Hello, I am in need of assistance in learning how to read in multiple names into
ID: 3545949 • Letter: H
Question
Hello,
I am in need of assistance in learning how to read in multiple names into my main function, using a C string, and I want to use a pointer to put the C string containing all of the names into a function.
As you can see, there will be between 1 and 20 names that I need to record. So what I need you to teach me (or show me) is how to read in 1-20 names and then after reading them, put them into a function that will then print out all of the names. You can do that by using the function at the very bottom called printnames.
If you need to modify any of the code already written then please do, however, do not introduce things that I haven't mentioned or written into my program.
#include <stdio.h>
#include <cstring>
void main() {
int students, assignments;
char names[15];
do {
printf("How many students are there (between 1 and 20)?");
scanf("%d", &students);
if (students < 1 || students > 20)
printf ("Number of students must be between 1 and 20. ");
} while (students < 1 || students > 20);
do {
printf("How many assignments are there (between 1 and 10)?");
scanf("%d", &assignments);
if (assignments < 1 || assignments > 10)
printf ("Number of assignments must be between 1 and 10. ");
} while (assignments < 1 || assignments > 10);
int i;
for(i=0; i < students; i++){
printf("Student name:");
scanf("%s", names);
printf("%s", names);
}
}
void printnames() {
}
Explanation / Answer
#include <stdio.h>
void main() {
int students, assignments;
do{
printf("How many students are there (between 1 and 20)?");
scanf("%d", &students);
if (students < 1 || students > 20)
printf ("Number of students must be between 1 and 20. ");
}while(students < 1 || students > 20);
char names[students][15];
do{
printf("How many assignments are there (between 1 and 10)?");
scanf("%d", &assignments);
if(assignments < 1 || assignments > 10)
printf("Number of assignments must be between 1 and 10. ");
}while(assignments < 1 || assignments > 10);
int i;
for(i = 0; i < students; i++){
printf("Student %d name: ", i + 1);
scanf("%s", names[i]);
}
printf("The students are: ");
for(i = 0; i < students; i++){
printnames(names[i]);
}
}
void printnames(char array[]){
printf("%s ", array);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.