Hi, I'm trying to write a programme that will take user input strings containing name, surname and city of residence separated by spaces and extract each one and print them out individually.
Here's what I have so far.
#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
int main()
{
char name[4][80];
char buffer1 [80];
char buffer2 [80];
char buffer3 [80];
int i,j,k,q,word_size,start_pos,end_pos,name_size,city_start,city_end,city_length;
cout<<"Enter three names and cities of residance"<<"\n";
gets( name[0]);
gets( name[1]);
gets( name[2]);
cout<<"initialise check"<<"\n";
cout<<"\n";
cout<<"\n";
cout<< name[0]<< "\n";
cout<< name[1]<< "\n";
cout<< name[2]<< "\n"<<"\n";
for (i=0; i<=2; i++)
{ j=0;
while (isspace (name[i][j]) )
{j=j+1;
}
k=j;
while(!isspace(name[i][k])) k=k+1; //advances through the first name
name_size=k-j;
for (q=0; q<name_size; q++)
{
// this generates the name
buffer1[q] = name[i][j];
j++;
}
buffer1[j]='\0';//this is the null char to terminate surname name
cout<<"Name "<<i+1<<": "<<buffer1<<"\n";
while(isspace(name[i][k])) k=k+1; // advances through the next block of spaces
start_pos=k;
while(!isspace(name[i][k])) k=k+1;// advances through the surname
end_pos=k;
word_size= end_pos - start_pos;
// check word size of first char
for (q=0; q<word_size; q++)
{
// this generates the surname
buffer2[q] = name[i][start_pos];
start_pos++;
}
buffer2[start_pos]='\0';//this is the null char to terminate surname name
cout << "Surname "<<i+1<<": "<<buffer2 << "\n";
while(isspace(name[i][k])) k++;
city_start=k;
while(!isspace(name[i][k])) k++;
city_end=k;
city_length=city_end-city_start;
for (q=0; q<city_length; q++)
{
// this generates the city
buffer3[q] = name[i][city_start];
city_start++;
}
buffer3[city_start]='\0';//this is the null char to terminate surname name
cout<<"City "<<i+1<<": "<<buffer3<<"\n";
cout<<"\n"<<"\n";
}
return 0;
}
This code is working to an extent but some of the results have extra characters at the end. Also you have to put a space after city in the input in order to stop counting "city_end". Is there any way around this?
Thanks