Issue with array of pointers - c

I'm writing a program to alphabetize inputted names and ages. The ages are inputted separately, so I know I need to use an array of pointers to tie the ages to the array of names but I can't quite figure out how to go about doing it. Any ideas?
So far, my program only alphabetizes the names.
/* program to alphabetize a list of inputted names and ages */
#include <stdio.h>
#define MAXPEOPLE 50
#define STRSIZE
int alpha_first(char *list[], int min_sub, int max_sub);
void sort_str(char *list[], int n);
int main(void)
{
char people[MAXPEOPLE][STRSIZE];
char *alpha[MAXPEOPLE];
int num_people, i;
char one_char;
printf("Enter number of people (0...%d)\n> ", MAXPEOPLE);
scanf("%d", &num_people);
do
scanf("%c", &one_char);
while (one_char != '\n');
printf("Enter name %d (lastname, firstname): ", );
printf("Enter age %d: ", );
for (i = 0; i < num_people; ++i)
gets(people[i]);
for (i = 0; i < num_people; ++i)
alpha[i] = people[i];
sort_str(alpha, num_people);
printf("\n\n%-30s5c%-30s\n\n", "Original List", ' ', "Alphabetized List");
for (i = 0; i < num_people; ++i)
printf("-30s%5c%-30s\n", people[i], ' ', alpha[i]);
return(0);
}
int alpha_first(char *list[], int min_sub, int max_sub)
{
int first, i;
first = min_sub;
for (i = min_sub + 1; i <= max_sub; ++i)
if (strcmp(list[i], list[first]) < 0)
first = i;
return (first);
}
void sort_str(char *list[], int n)
{
int fill, index_of_min;
char *temp;
for (fill = 0; fill < n - 1; ++fill){
index_of_min = alpha_first(list, fill, n - 1);
if(index_of_min != fill){
temp = list[index_of_min];
list[index_of_min] = list[fill];
list[fill] = temp;
}
}
}

Most of your printfs are syntax errors, as in
printf("Enter name %d (lastname, firstname): ", );
printf("Enter age %d: ", );
or bomb right away, since you pass an int (' ') as a pointer:
printf("\n\n%-30s5c%-30s\n\n", "Original List", ' ', "Alphabetized List");
As a first step, get all your %s right and show us what you really compiled, not some random garbage. And crank your compiler's warning level to the maximum, you need it! What is
#define STRSIZE
supposed to mean when STRSIZE is used as an arary dimension? You have a serious cut&paste problem, it would appear.

Creating a struct would probably be easier: i.e
struct person {
char name[STRSIZE];
int age;
}
Otherwise, if you must do it the way you're trying, just create an extra array of the indexes. When you move a name, you also move the index on the array... when you're done sorting names, just sort the ages to match the indexes.

Related

Printing out values in an array not working as expected

I was tasked with inputting student information based on a given struct, where each field of information is to be typed in one line, separated by a space, then the student id is sorted incrementally, and then print out the information, each student on a new line. The problem is while I thought my code was good, the print part keeps giving fractured results and overall just not printing out the correct values. Where should I fix this?
Here's my code:
#include <stdio.h>
typedef struct
{
char id[8];
int year;
}student;
int main() {
student std[100];
int i, j, num, tmp;
printf("So sinh vien:\n");
scanf("%d", &num);
printf("Nhap thong tin sinh vien:\n");
for(i=0; i <= num; i++)
{
scanf("%c %d\n", &std[i].id, &std[i].year);
}
for(i=0; i < num; i++)
{
for (j=1; j< num; j++)
{
if (std[i].id > std[j].id)
{
tmp = *std[i].id
*std[i].id = *std[j].id;
*std[j].id = tmp;
}
}
}
for(i=0; i < num; i++)
{
printf("%c ", std[i].id);
printf("%d\n", std[i].year);
}
return 0;
}
My output is
So sinh vien:
3
Nhap thong tin sinh vien:
12324521 2003
12341552 2002
12357263 2001
Σ 12324521
≡ 3
ⁿ 2341552
Check the return value of scanf() otherwise you may be operating on uninitialized variables.
Check that num less than the 100 records you allocated for student, or even better use a vla along with a check to avoid large input from smashing the stack.
You input num then read num+1 records but later you only print num records.
As you read a character with "%c" the first input with be the \n from the previous scanf().
The struct contains a char id[8] but you only read a single character into it. Read a string instead.
In sort you use > to compare the first letter of id. You probably want to use strcmp() to compare strings.
In sort section you use a int tmp for storing a character of id (which is ok) but then you write an int which is no good.
In sort you only swap the ids. You probably want to swap the entire record not just the ids.
It seems to be an exchange sort. Use a function, and also at least for me the algorithm didn't work as the inner loop variable should start at j=i+1 not 1.
In your print char id[8] as a single char instead of string.
Moved print functionality to a function. This allows you, for instance, to print the students before and after the sort() during debugging.
Minimizing scope of variables (i and j are now loop local, tmp is only used in the swap() function). This makes code easier to reason about.
#include <stdio.h>
#include <string.h>
#define ID_LEN 7
#define str(s) str2(s)
#define str2(s) #s
typedef struct {
char id[ID_LEN+1];
int year;
} student;
void swap(student *a, student *b) {
student tmp = *a;
*a = *b;
*b = tmp;
}
void print(size_t num, student std[num]) {
for(size_t i=0; i < num; i++)
printf("%s %d\n", std[i].id, std[i].year);
}
// exchange sort
void sort(size_t num, student std[num]) {
for(size_t i=0; i < num - 1; i++)
for (size_t j=i+1; j < num ; j++)
if(strcmp(std[i].id, std[j].id) > 0)
swap(&std[i], &std[j]);
}
int main() {
printf("So sinh vien:\n");
size_t num;
if(scanf("%zu", &num) != 1) {
printf("scanf() failed\n)");
return 1;
}
if(num > NUM_MAX) {
printf("Too many students\n");
return 1;
}
student std[num];
printf("Nhap thong tin sinh vien:\n");
for(size_t i=0; i < num; i++)
if(scanf("%" str(ID_LEN) "s %d", std[i].id, &std[i].year) != 2) {
printf("scanf() failed\n");
return 1;
}
sort(num, std);
print(num, std);
}
and here is an example run:
So sinh vien:
3
Nhap thong tin sinh vien:
aaa 1
zzz 2
bbb 3
aaa 1
bbb 3
zzz 2
printf("%c ", std[i].id);
should be
printf("%s ", std[i].id);
%c means a single char.

Stack around the variable was corrupted with pointer arithmetics

With the code below, I'd always run into "Stack around the variable 'UserCode' was corrupted.
If I'm not mistaken, when I do userCode = (char*)malloc(sizeof(char)*N);, shouldn't it create an "array" with size of char*n ? I'm guessing my issue is either with my declaration of an array, or my pointer arithmetic.
Any help would be highly appreciated.
#include "stdafx.h"
#include <math.h>
int userPrompt1() {
int numOfAlphabets = 0;
printf("Please enter a number from 1 to 8 to choose how many alphabets you want\n");
scanf_s(" %d", &numOfAlphabets);
if (numOfAlphabets > 8 || numOfAlphabets < 0) {
printf("Sorry! Invalid number entered. Try again. \n");
numOfAlphabets = userPrompt1();
}
return numOfAlphabets;
}
int userPrompt2() {
int numOfLetters = 0;
printf("Please enter the number of letters you want to guess\n");
scanf_s(" %d", &numOfLetters);
if (numOfLetters < 0) {
printf("Sorry! Invalid number entered. Try again. \n");
numOfLetters = userPrompt2;
}
return numOfLetters;
}
int tryCalculator(int K, int N) {
int tries = 0;
tries = 1 + ceil(N * log2(K));
return tries;
}
void codeGenerator(char codeGuessIn[], char letters[], int size) {
for (int i = 0; i < size; i++) {
int rando = rand() % size;
codeGuessIn[i] = letters[rando];
printf(" %c", codeGuessIn[i]);
}
printf("\n");
}
void codeChecker(char codeGuessIn[], char generatedCode[], int size) {
int correctAlphabets = 0;
for (int i = 0; i < size; i++) {
if (codeGuessIn[i] == generatedCode[i]) {
correctAlphabets++;
}
}
printf(" %d in correct place \n", correctAlphabets);
}
void getUserCode(int size, char *userCode[]) {
for (int i = 0; i < size; i++) {
printf("Please enter letter #%d \n", i+1);
getchar();
scanf_s(" %c", &userCode[i]);
}
}
int main(void)
{
char letters[8] = { 'A','B','C','D','E','F','G','H' };
char *generatedCode; //array to hold generated code
char *userCode; // array to hold generated code.
int K = userPrompt1(); //how many different alphabets in code
int N = userPrompt2(); //how many letters in code
int tries = tryCalculator(K, N);
//int gameEnd = 1;
userCode = (char*)malloc(sizeof(char)*N);
generatedCode = (char*)malloc(sizeof(char)*N);
codeGenerator(generatedCode, letters, N);
getUserCode(N, &userCode);
//codeChecker(userCode, generatedCode, N);
return 0;
}
void getUserCode(int size, char *userCode[]) {
scanf_s(" %c", &userCode[i]);
Here, userCode[i] is a char * (pointer-to-char), &userCode[i] is a char ** (pointer-to-pointer-to-char), and scanf("%c") expects a char *. A good compiler would warn about that.
I think what you meant to do here is something like:
void getUserCode(int size, char *userCode) {
scanf_s(" %c", &userCode[i]);
}
int main(void) {
char *userCode = malloc(N);
getUserCode(N, userCode);
}
The printf(), getchar(), scanf() combination here reeks of the bad habits created by scanf: you're discarding the first character entered by the user because you're relying on an extra character in the input buffer.
See http://c-faq.com/stdio/scanfprobs.html and read full lines of input with fgets() instead of using scanf().
Also,
int userPrompt2() {
int numOfLetters = 0;
...
numOfLetters = userPrompt2;
}
You're assigning a function pointer to an int. (A normal compiler should warn about this.) If the idea here is to call the function again to repeat the prompt in case the user enters something silly, it's probably a better idea to use a loop instead of a recursive call anyway.

Proper use of structures and pointers

I have to declare a vector with the "struct" type which, for every n students, it creates a value for the group that student belongs to (which is like a counter), their names and their grades.
The program has to output the name of the students with the highest grade found in these groups. I have to allocate the vector on the heap (I only know the theoretical explanation for heap, but I have no idea how to apply it) and I have to go through the vector using pointers.
For example if I give n the value 4, there will be 4 students and the program will output the maximum grade together with their names as shown here.
This will output Ana 10 and Eva 10.
I gave it a try, but I have no idea how to expand it or fix it so I appreciate all the help I can get with explanations if possible on the practical application of heap and pointers in this type of problem.
#include <stdio.h>
#include <stdlib.h>
struct students {
int group;
char name[20];
int grade;
};
int main()
{
int v[100], n, i;
scanf("%d", n);
for (i = 0; i < n; i++) {
v[i].group = i;
scanf("%s", v[i].name);
scanf("%d", v[i].grade);
}
for (i = 0; i < n; i++) {
printf("%d", v[i].group);
printf("%s", v[i].name);
printf("%d", v[i].grade);
}
return 0;
}
Here I was just trying to create the vector, nothing works though..
It appears, int v[100]; is not quite what you want. Remove that.
You can follow either of two ways.
Use a VLA. After scanning the value of n from user, define the array like struct students v[n]; and carry on.
Define a fixed size array, like struct students v[100];, and use the size to limit the loop conditions.
That said,
scanf("%d", n); should be scanf("%d", &n);, as %d expects a pointer to integer type argument for scanf(). Same goes for other cases, too.
scanf("%s", v[i].name); should better be scanf("%19s", v[i].name); to avoid the possibility of buffer overflow by overly-long inputs.
Even though you are asking for the number of students (groups) using scanf, you hardcoded the upper bound of this value using v[100]. So, I passed your input variable n (the number of students) to malloc in order to allocate the space you need for creating an array of n students.
Also, I used qsort to sort the input array v where the last element would be the max value. Here qsort accepts an array of structs and deference the pointers passed to the comp function to calculate the difference of the comparison.
Finally, I printed the sorted array of structs in the last loop.
#include <stdio.h>
#include <stdlib.h>
struct students {
int group;
char name[20];
int grade;
};
int comp(const void *a, const void *b)
{
return ((((struct students *)a)->grade > ((struct students *)b)->grade) -
(((struct students *)a)->grade < ((struct students *)b)->grade));
}
int main()
{
int n;
printf("Enter number of groups: ");
scanf("%d", &n);
printf("\n");
struct students *v = malloc(n * sizeof(struct students));
int i;
for(i = 0; i < n; i++)
{
v[i].group = i;
printf("\nName: ");
scanf("%s", v[i].name);
printf("Grade: ");
scanf("%d", &v[i].grade);
}
qsort(v, n, sizeof(*v), comp);
for(i = 0; i < n; i++)
{
printf("Group %d, Name %s, grade %d\n", v[i].group, v[i].name, v[i].grade);
}
return (0);
}
You need to replace the standalone array v[100], with an array of structs referencing your structure:
struct students v[100];
However, if you want to use malloc to allocate memory on the heap, you will need to do something like this:
struct students *students = malloc(n * sizeof(struct students));
/* Check void* return pointer from malloc(), just to be safe */
if (students == NULL) {
/* Exit program */
}
and free the requested memory from malloc() at the end, like this:
free(students);
students = NULL;
Additionally, adding to #Sourav Ghosh's answer, it is also good to check the return value of scanf(), especially when dealing with integers.
Instead of simply:
scanf("%d", &n);
A more safe way is this:
if (scanf("%d", &n) != 1) {
/* Exit program */
}
With all this said, your program could look something like this:
#include <stdio.h>
#include <stdlib.h>
#define NAMESTRLEN 20
typedef struct { /* you can use typedef to avoid writing 'struct student' everywhere */
int group;
char name[NAMESTRLEN+1];
int grade;
} student_t;
int
main(void) {
int n, i;
printf("Enter number of students: ");
if (scanf("%d", &n) != 1) {
printf("Invalid input.\n");
exit(EXIT_FAILURE);
}
student_t *students = malloc(n * sizeof(*students));
if (!students) {
printf("Cannot allocate memory for %d structs.\n", n);
exit(EXIT_FAILURE);
}
for (i = 0; i < n; i++) {
students[i].group = i;
printf("Enter student name: ");
scanf("%20s", students[i].name);
printf("Enter students grade: ");
if (scanf("%d", &(students[i].grade)) != 1) {
printf("Invalid grade entered.\n");
exit(EXIT_FAILURE);
}
}
printf("\nStudent Information:\n");
for (i = 0; i < n; i++) {
printf("Group: %d Name: %s Grade: %d\n",
students[i].group,
students[i].name,
students[i].grade);
}
free(students);
students = NULL;
return 0;
}

Quick sort function works only if last value is the largest

I'm trying to practice using Quick Sort in C. My program is a simple array of structs that takes in command line args (name1 age 1 name2 age2...etc) and outputs said ages in descending order.
It works correctly ONLY if the last age inputted is the largest. Other than that I either get no output or Seg Fault 11. Does anyone have any ideas?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NameLen 80
void print_struct();
struct people
{
char name [NameLen + 1];
int age;
}; //defining a structure//
typedef struct people PERSON;
void quicksort(struct people list[],int,int);
int main(int argc, const char * argv[])
{
int i,j;
j = 0;
int l = ((argc/2)-1);
struct people list[l]; //maximum size of array of structs
if (argc %2 == 0) //if the number of arguments is an even number
{
printf("Invalid Arguments!\n");
printf("Usage : ./hw5 name1 age1 name2 age2 ... "); //print error message and correct program usage
exit(0);
}
printf("You have entered %d persons(s) into the program \n",(argc/2));
for (i=1; i < argc; i+=2)
{
strcpy(list[j].name, argv[i]);
list[j].age = atoi(argv[i+1]);
if(list[j].age == 0)
{
printf("...Invalid age <=0. Try again.\n");
exit(0);
}
j++;
}
printf("Unsorted Names: \n");
print_struct(&list,argc);
printf ("Sorted by Age: \n");
quicksort(list,0 ,j);
for(i=0;i<j;i++){
printf("Name : %s| Age : %d\n", list[i].name, list[i].age);}//possible error here?
//Quicksort Function
Perhaps the problem is the value of j. Is j the length of list? Or the length of list - 1?
It seems like this would be what you would want:
j = length of list
printf ("Sorted by Age: \n");
quicksort(list,0 ,j-1);
for(i=0;i<j;i++){
printf("Name : %s| Age : %d\n", list[i].name, list[i].age);}
The quicksort function is fine. The issue is that you're calling it wrong:
quicksort(list,0 ,j);
The values you're passing in for first and last represent the index of the first and last elements. As evident from how you use j to loop through the elements, j is the number of elements. That means that the last element has index j-1.
So you're passing a value for last that is one element past the end of the array. When you then try to read/write this bogus element, you invoke undefined behavior which in your case (fortunately) leads to a segfault.
Pass in the actual index of the last element (i.e. one less than the size) and it runs successfully.
quicksort(list,0 ,j - 1);
Your loops are incorrect:
while(list[i].age<=list[pivot].age&&i<last)
i++;
It is possible for this loop to end with i == last, which is bad because you attempt to swap the value, which would be out of scope of the array.
while(list[j].age>list[pivot].age)
j--;
Here, since j starts as last, you start right off with reading outside of the array.
One possible remedy is to move j backwards first, then test (do-while style). Then, increment i, testing against the decremented j.
do --j; while(list[j].age>list[pivot].age);
do ++i; while(list[i].age<=list[pivot].age&&i<j);
I made the code a little bit simple (changed the array of chars to just a char to make it more simple as possible).
My thoughts are that when you call:
quicksort(list,0 ,j);
What you should call is:
quicksort(list,0 ,j-1);
Because the last parameter must be the array lenght minus 1, the last position.
I got no seg fault, when running your code, or the one I modified, if it is possible, double check the strings you are using as input.
Here is "my" vesion of the code.
Hope it helps.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NameLen 80
void print_struct();
struct people
{
char name;
int age;
}; //defining a structure//
typedef struct people PERSON;
void quicksort(struct people list[],int,int);
int main(int argc, const char * argv[])
{
int i,j;
j = 10;
struct people list[10]; //maximum size of array of structs
for (i=0; i < 10; i++)
{
list[i].name = 'a';
list[i].age = 10-i;
}
printf("Unsorted Names: \n");
for(i=0;i<j;i++){
printf("Name : %c| Age : %d\n", list[i].name, list[i].age);}//possible error here?
printf ("Sorted by Age: \n");
quicksort(list,0 ,j-1);
for(i=0;i<j;i++){
printf("Name : %c| Age : %d\n", list[i].name, list[i].age);}//possible error here?
}
void quicksort(struct people list[],int first,int last)
{
struct people temp;
int i,j,pivot;
if(first<last){
pivot=first;
i=first;
j=last;
while(i<j)
{
while(list[i].age<=list[pivot].age&&i<last)
i++;
while(list[j].age>list[pivot].age)
j--;
if(i<j){
temp=list[i];
list[i]=list[j];
list[j]=temp;
}
}
temp=list[pivot];
list[pivot]=list[j];
list[j]=temp;
quicksort(list,first,j-1);
quicksort(list,j+1,last);
}
}
after applying all the comments, this is the resulting code, which cleanly compiles, but will not link due to the two missing functions:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NAME_LEN (80)
struct people
{
char name [NAME_LEN + 1];
int age;
}; //defining a structure//
typedef struct people PERSON;
// print_struct( ptrToList, numElements )
void print_struct( PERSON *, int );
// quicksort( ptrToList, firstOffset, numElements )
void quicksort(struct people list[],int,int);
int main(int argc, const char * argv[])
{
//int i,j;
//j = 0;
//int l = ((argc/2)-1);
int l = argc/2;
struct people list[l]; //maximum size of array of structs
if (argc %2 == 0) //if the number of arguments is an even number
{
//printf("Invalid Arguments!\n");
fprintf( stderr, "Invalid Arguments!\n" );
//printf("Usage : ./hw5 name1 age1 name2 age2 ... "); //print error message and correct program usage
fprintf( stderr, "Usage : %s name1 age1 name2 age2 ... ", argv[0]);
// exit(0);
exit( EXIT_FAILURE );
}
//printf("You have entered %d persons(s) into the program \n",(argc/2));
printf("You have entered %d persons(s) into the program \n", l);
//for (int i=1; i < argc; i+=2)
for (int i=1, j=0; j < l; i+=2, j++)
{
//strcpy(list[j].name, argv[i]);
memset( list[i].name, '\0', NAME_LEN+1);
strncpy( list[j].name, argv[i], NAME_LEN );
list[j].age = atoi(argv[i+1]);
if(list[j].age == 0)
{
fprintf( stderr, "...Invalid age <=0. Try again.\n");
//exit(0);
exit( EXIT_FAILURE );
}
//j++;
}
printf("Unsorted Names: \n");
//print_struct(&list,argc);
print_struct( list, l );
//printf ("Sorted by Age: \n");
//quicksort(list,0 ,j);
quicksort( list, 0, l );
printf ("Sorted by Age: \n");
// //for(i=0;i<j;i++)
//for( int i=0; i<l; i++ )
//{
// printf("Name : %s| Age : %d\n", list[i].name, list[i].age);
//}//possible error here?
//}
print_struct( list, l);
} // end function: main
//Quicksort Function

Print the last string name in C

I am trying to learn C and here i got a program in which we have to take the input from the user as n number os strings, compare it and arrange it in a alphabetical order. After arranging them in a alphabetical order , i have to only print the last name which was occurring in the order.
Here is the code for the above problem:
#include<stdio.h>
#include<string.h>
int main()
{
int i,j,m,n,len;
char a[50][50],temp[100];
char last ;
printf("Enter the number of elements you wish to order : ");
scanf("%d",&m);
printf("\nEnter the names :\n");
for (i=0;i<m;i++){
scanf("%s",a[i]);
}
for (i=0;i<m;i++){
for (j=i+1;j<m+1;j++) {
if (strcmp(a[i],a[j])>0) {
strcpy(temp,a[i]);
strcpy(a[i],a[j]);
strcpy(a[j],temp);
}
}
}
printf("\n\nSorted strings are : ");
for (i=0;i<m+1;i++){
printf("%s \n",a[i]);
}
return 0;
}
~
The Answer goes this way:
Enter the number of elements you wish to order : 4
Enter the names :
territory
states
hello
like
Sorted strings are : S$???
hello
like
states
territory
My question goes that why am i getting "S$???" and i want only the last word "territory should be printed out not all the names".
Can anyone let me know where am i going wrong? It will be a great help.
Thanks
Tanya
You are sorting m+1 strings with indexes [0..m]. But you input only m strings.
Your indexes should never go above m-1.
\Check this code
In your code you get input as 4
then
a[0]=territory
a[1]=states
a[2]=hello
a[3]=like
But your code runs upper loop at most 3 time then i=3
In next loop j=i+1 then j=4
but a[4]=not exists
Thats why "S$???" occurs
Solution:
#include<stdio.h>
#include<string.h>
int main() {
int i, j, m, n, len;
char a[50][50], temp[100];
char last;
printf("Enter the number of elements you wish to order : ");
scanf("%d", &m);
printf("\nEnter the names :\n");
for (i = 0; i < m; i++) {
scanf("%s", a[i]);
}
for (i = 0; i < m - 1; i++) { // m - 1 enough maximum i = 2;
for (j = i + 1; j < m; j++) { // j maximum j = i + 1 j = 3
if (strcmp(a[i], a[j]) > 0) {
strcpy(temp, a[i]);
strcpy(a[i], a[j]);
strcpy(a[j], temp);
}
}
}
printf("\n\nSorted strings are : "); // print all words in sorted order
for (i = 0; i < m; i++) {
printf("%s \n", a[i]);
}
printf("Last Word:\n");
printf("%s\n", a[m - 1]); // a[3] contains last name
return 0;
}
this was my program it worked for me in turbo c++
#include<conio.h>
#include<iosream.h>
#include<ctype.h>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
void main()
{
clrscr();
char name[100];
int c=0;
// to take the name including spaces
gets(name);
//this line is to print the first character of the name
cout<<name[0];
//this loop is to print the fist character which is there after every space
for(int l=0;name[l]!='\0';l++)
{
if(name[l]==' ')
{
cout<<"."<<name[l+1];
//l+1 is used because l is the space and l+1 is the character that we need
}
}
//this loop is to find out the last space in the entire sting
for(int i=0;name[i]!='\0';i++)
{
if(name[l+1]==NULL)
{
//here we fond the last space in the string
for(int j=i;name[j]!=' ';j--)
{
c=j+1;
}
// c=j+1 is used bacause we have already taken the first letter of the that word
//no need of taking it again
}
}
//this loop starts from the last space and the position(of space) is stored in k
for(int k=c;name[k]!='\0';k++)
{
cout<<name[k];
}
getch();
}
output:
anentt ranjan shukla
a.r.shukla

Resources