?
Solved

C++ simple question..

Posted on 2005-03-10
17
Medium Priority
?
208 Views
Last Modified: 2010-04-01
This is an Array based question....can somebody please help me to solve this..

Question: A western style name is held in an array of characters called 'namestr'; the full nameis delimited by quotes thus;
___________________________________________________________
                                                     |
1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  
___________________________________________________________|
'   P  A  U  L     J  O  H   N        W   O    O    D    S   '  
___________________________________________________________|

The Name is required to be in following format;

<last name>,<Initial for first name>,<Initial for second fore name>

Can somebody help me to write a C++ code for above criteria?
0
Comment
Question by:nishasrilankan
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
  • 3
  • +5
17 Comments
 
LVL 8

Assisted Solution

by:novitiate
novitiate earned 200 total points
ID: 13514196
int main()
{
      
      char namestr[] = "\'PAUL JOHN WOODS\'";      
      char lastname[32];
      char initF;
      char initM;
      
      sscanf(namestr, "%*c%s%*c%c%*s%*c%c%*s", lastname, &initF, &initM);
      printf("%s %c %c\n", lastname, initF, initM);
      return 0;
}

_novi_
0
 
LVL 55

Expert Comment

by:Jaime Olivares
ID: 13514255
A different approach:

ConvertName(char *input, char *output)     // output must point to a proper sized buffer
{
        char first, second;
        first = *(input+1);
        second = 0;
        while (*input && *input!=' ')
              input++;   // advance up to first space area
        while (*input == ' ')  // more spaces?
              input++;
        *second = *input;  // obtain second initial
        while (*input && *input!=' ')
             input++;  // advance up to second space area
        while (*input == ' ')  // more spaces?
              input++;
        // input now points to last name

       sprintf(output, "%*.s, %c, %c", strlen(input)-1, input, first, second);     // maybe this is not the correct order, please correct if so
}
0
 
LVL 2

Expert Comment

by:avinash_sahay
ID: 13514375
You wrote:-
"The Name is required to be in following format;

<last name>,<Initial for first name>,<Initial for second fore name>"

What is the delimiter between these parts of a name? I understand from your question that two names are separated by quotes. But what separates the last name and the initial for first name?
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Assisted Solution

by:amar_r
amar_r earned 200 total points
ID: 13515464
novitiate,

 correction to your sscanf():
sscanf(namestr, "'%[^ ] %c%*[^ ] %c", lastname, &initF, &initM);



 -amar
0
 
LVL 22

Assisted Solution

by:grg99
grg99 earned 400 total points
ID: 13515897
ahh, jamie, your code is mostly foobar-- starting with first and second being chars, then taking *(input+1), then printing out strings in %c format.  

When I submit untested code I prefix it with some disclaimer like "write it something like this:"
0
 
LVL 55

Assisted Solution

by:Jaime Olivares
Jaime Olivares earned 400 total points
ID: 13516328
> starting with first and second being chars, then taking *(input+1)
This can be easily managed (see below)

>then printing out strings in %c format.  
I don't print out strings in %c format but characters

>When I submit untested code I prefix it with some disclaimer like "write it something like this:"
Indeed I have tested it with sample string above. I use to write "something like this" but I decided to use the word APPROACH.
At least in my country this is lexically correct: approach ----> near to solution.

PS. If you want a ***better approach***
ConvertName(char *input, char *output)     // output must point to a proper sized buffer
{
        if (strlen(input)<3)
             *output = 0;   // string too shorter
        char first, second;
        first = *(input+1);
        while (*input && *input!=' ')
              input++;   // advance up to first space area
        while (*input == ' ')  // more spaces?
              input++;
        *second = *input;  // obtain second initial
        while (*input && *input!=' ')
             input++;  // advance up to second space area
        while (*input == ' ')  // more spaces?
              input++;
        // input now points to last name

       sprintf(output, "%*.s, %c, %c", strlen(input)-1, input, first, second);
}

0
 
LVL 22

Assisted Solution

by:grg99
grg99 earned 400 total points
ID: 13516481
You could not have tested it, you have

* second = * input;

... which can't ever compile.

0
 
LVL 39

Assisted Solution

by:itsmeandnobodyelse
itsmeandnobodyelse earned 400 total points
ID: 13516706
Or that:

#include <string>
#include <sstream>
using namespace std;

   string name = "'John Paul Woods'";
   istringstream iss(name.substr(1, name.length()-2));
   string first_name, middle_name, last_name;
   iss >> first_name >> middle_name >> last_name;
   ostringstream oss;
   oss << last_name << ", " << first_name[0] << ". " << middle_name[0] << ".";
   name = oss.str();

Regards, Alex
0
 
LVL 6

Assisted Solution

by:SJT2003A
SJT2003A earned 200 total points
ID: 13517751
Alex,
   Your solution is better and accurate for the question.

As the requester asked for a C++ solution and all other above solutions are written in a typical C program, this is  better-off to the question.

Good day :)

0
 
LVL 55

Assisted Solution

by:Jaime Olivares
Jaime Olivares earned 400 total points
ID: 13521592
>You could not have tested it, you have
>* second = * input;
>... which can't ever compile

I have tested, corrected the error on my compiler and forgotten to correct in the code I have written directly on this page. But don't worry, I don't need a babysitter to say me I have made my homework bad.
0
 
LVL 2

Accepted Solution

by:
avinash_sahay earned 200 total points
ID: 13523064
Since the solution is required in C++, we can use strtok.
0
 
LVL 6

Author Comment

by:nishasrilankan
ID: 13523597
itsmeandnobodyelse: Your code is giving required output with simple modifications..
//#include <string>

#include <sstream>
#include <iostream>
using namespace std;

void main(){

   string name = "'John Paul Woods'";
   istringstream iss(name.substr(1, name.length()-2));
   string first_name, middle_name, last_name;
   iss >> first_name >> middle_name >> last_name;
   ostringstream oss;
   oss << last_name << ", " << first_name[0] << ". " << middle_name[0] << ".";
   name = oss.str();
   cout<<first_name[0]<<". "<<middle_name[0]<<". "<<last_name<<endl;
}





//even after I commenting '#include <string>' line the code still compiled. So whats the purpose of inserting that line

and...actually I want to implement the solution with using a character array. can somebody tell me how to implement this using character array???
0
 
LVL 2

Expert Comment

by:avinash_sahay
ID: 13523628
//Using strtok
#include <string.h>

void main()
{
      //The name is stored in a char array named szName.
      char szName[] = "'John Paul Woods'";

      //strtok changes a string. So, copy szName in another char array in case
      //we want to retain the original one.
      char* szNameCopy = new char[strlen(szName) + 1];
      strcpy(szNameCopy, szName);

      //The parts of a name are separated by whitespace character.
      char* szFirstName = strtok(szNameCopy, " ");//Get the first name
      
      //The first name starts with quote. Advance szFirstName by one character
      //to get rid of that.
      szFirstName++;//Now, szFirstName contains first name without quote

      char* szMiddleName = strtok(NULL, " ");//Get the middle name

      char* szLastName = strtok(NULL, " ");//Get the last name

      //The last name ends in a quote. Put null character at that position
      //to remove the quote.

      szLastName[strlen(szLastName)] = '\0';//Now, szLastName contains last name without quote.

      //Note: Before deleting szNameCopy, make sure that
      //you have stored szFirstName, szMiddleName and szLastName to wherever
      //you want as delete will destroy the contents of even these three.
      delete []szNameCopy;
}
0
 
LVL 39

Assisted Solution

by:itsmeandnobodyelse
itsmeandnobodyelse earned 400 total points
ID: 13523653
>>> ...commenting '#include <string>' line the code still compiled. So whats the purpose of inserting that line

#include <sstream> already includes <string> header

Generally you should include all headers of the used standard objects even if some of them already mutual include. That makes it easier to change an implementation, e. g. from string streams  to strtok, and not getting compile errors because of missing header includes. All standard header files are protected to not being included twice.

Regards, Alex
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 13523687
>>>> Since the solution is required in C++, we can use strtok.

The statement is wrong. You should say "Though the question is asked in the C++ topic area, a solution in 'C' might be a valid answer."

Howvever, I couldn't see any advantage on using a non C++ solution here.

Regards, Alex
0
 
LVL 2

Expert Comment

by:avinash_sahay
ID: 13523722
I am not saying that we must use strtok. I mentioned this as an option as the code looks simple with strtok (if we are using char array as mentioned in the first post of this thread).
0
 
LVL 2

Expert Comment

by:avinash_sahay
ID: 13523745
Moreover, for a complete C++ solution, I would use string rather than char array (like you have done). But the person who has started this thread has mentioned that she is using an array of characters.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
Suggested Courses

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question