I am trying to pass a number N
and a set of string S
as input. Here the string S
contains a name <abc>
followed by a comma ,
and then followed by a multiple digit integer k
.
The program must display the name with the highest corresponding number.
Consider the following set of inputs:
4
Will,13
Bob,7
Mary,56
Gail,45
For which the output must be:
Mary
since the number corresponding to Mary
is 56
which is the highest.
The problem I am facing is to get the name and number in two arrays namely w[][]
& a[][]
.
Here I have tried two-dimensional arrays, but I am not able to read the comma separated values.
Below is the logic I used for reference:
#include <stdio.h>
#include <ctype.h>
int main() {
char W[200][1000]; // Two dimensional arrays to store names
int a[200]; // To store the numbers
int i, n, max, pos;
scanf("%d", &n); // Number of Strings
for (i = 0; i < n; i++) {
scanf("%[^\n]s", W[i]); // To read the name
getchar(); // To read the comma
scanf("%d", &a[i]); // To read the number
}
printf("\n");
for (i = 0; i < n; i++) {
printf("W[%d] = %s a[%d] = %d\n", i, W[i], i, a[i]); // Displaying the values
}
// To find out the maximum value
max = a[0];
for (i = 0; i < n; i++) {
if (a[i] >= max) {
max = a[i];
pos = i;
}
}
printf("\n%s", W[pos]); // Print the name corresponding to the name
return 0;
}
So basically I want to extract the name before the comma (,
) into the character array and the number after the comma into the number array.
How can I make this code optimal now in C
?
A general advice: prefer heap allocated values (and use malloc
or realloc
& free
; read about C dynamic memory allocation) to large variables like char W[200][1000];
. I suggest to handle a char**W;
thing.
The program must display the name with the highest corresponding number.
Think a bit more. You don't need to store all the previously read numbers, and you should design your program to be able to handle a file of many millions (name, score) lines (without eating a lot of memory).
Then, scanf("%[^\n]s",W[i]);
is not doing what you want. Read carefully documentation of scanf
(and test its return value). Use fgets
-and preferably getline
if you have it- to read a line, then parse it (perhaps with sscanf
).
So basically I want to extract the name before the comma into the character array and the number after the comma into the number array.
Consider using standard lexing and parsing techniques, perhaps on every line.
PS. I don't want to do your homework.