i am trying to take input for name and return it with only the first letters of the name as capital....i am able to it the first name but m unable to move on to the second and last name.... please help..

string ToUpper(string n)
{
           for(int i=0;i<n.length();i++)

       
     {
                
                string m = n;
                for(int i = 1; i < m.length(); i++)
                m[i] = tolower(m[i]);
     
                if (n[i] >='a' && n[i] <='z')
                
                n[i]=n[i]-32;
                
                
                
                return m;
                return n;
     }
     
      }

Dani AI

Generated

Short summary and focused fixes tied to the replies from the thread: the original problem was twofold — reading only the first word and fragile per-character logic. started with a good idea, corrected the input-loop approach, provided a compact solution, and pointed to related discussion. The remaining pitfalls to watch for are: never return from inside the main scanning loop, avoid ASCII-only arithmetic on char, and cast to unsigned char before calling C ctype helpers to avoid UB.

A practical pattern is: (1) read the full line with getline, (2) validate allowed characters (letters, spaces, maybe - and '), (3) normalize capitalization so only the first letter of each word is upper-case. The example below uses a regex for validation and std::toupper/std::tolower for normalization; it also shows the simple do/while re-prompt pattern.

#include <string>
#include <regex>
#include <cctype>

// validation: letters plus internal space, hyphen or apostrophe
bool valid_name(const std::string &s) {
    static const std::regex rx(R"(^[A-Za-z]+(?:[ '-][A-Za-z]+)*$)");
    return std::regex_match(s, rx);
}

std::string capitalize_name(std::string s) {
    bool start = true;
    for (size_t i = 0; i < s.size(); ++i) {
        unsigned char uc = static_cast<unsigned char>(s[i]);
        if (std::isalpha(uc)) {
            s[i] = static_cast<char>(start ? std::toupper(uc) : std::tolower(uc));
            start = false;
        } else {
            start = (s[i] == ' ' || s[i] == '\'' || s[i] == '-');
        }
    }
    return s;
}

Loop example (do/while):

std::string line;
do {
    std::getline(std::cin, line);
    if (!valid_name(line))
        std::cout << "Invalid name — use letters, spaces, apostrophe or hyphen\n";
} while (!valid_name(line));
std::cout << capitalize_name(line) << '\n';

Troubleshooting notes: cast char to unsigned char before std::isalpha/std::toupper; regex is convenient but heavier; for Unicode (accented letters or non-Latin scripts) use a UTF-8 aware library (ICU or equivalent) instead of these byte-based helpers. For reference on the character helpers and regex: see std::isalpha and std::regex.

Recommended Answers

All 7 Replies

Here's my solution:

Cheers,
ninwa

I'm supposing you're obtaining user input by using:

cin >> name;

If you are, I suggest you read this thread. The problem with cin is it only takes input till a whitespace is found, so you're only using the first word.

hey thanks guys...with ur help i have got it... but i want to make a do while loop of it...can u tell me how to that...because if the name is having an integer or any other sign i have to output an error message and then again take input

{
    string n;
    string s;
    

  cout<<"Please enter your name :"<<flush;
  getline(cin, n);
   for(int i=1; i<n.length(); i++)
 { if (n[i]<='A'|| n[i]>='z' ||n[i]!=' ')
  cout<<"Error code 01: Name contains a character that is neither an alphabet nor a space"<<endl;

}  if(n[0]>='a' && n[0]<='z') n[0]-='a'-'A';


   for(int x=1; x<n.length(); x++)
   {
            if(n[x]>='a' && n[x]<='z' && n[x-1]==' ') n[x]-='a'-'A';
             else if(n[x]>='A' && n[x]<='Z') n[x]+='a'-'A';
  }
 
 cout<<n<<endl;

Version with loop:

bool Error = true;
while(Error)
{
{
string n;
string s;


cout<<"Please enter your name :"<<flush;
getline(cin, n);
for(int i=1; i<n.length(); i++)
{ if (n[i]<='A'|| n[i]>='z' ||n[i]!=' ')
{
Error = false;
cout<<"Error code 01: Name contains a character that is neither an alphabet nor a space"<<endl;
}

} if(n[0]>='a' && n[0]<='z') n[0]-='a'-'A';


for(int x=1; x<n.length(); x++)
{
if(n[x]>='a' && n[x]<='z' && n[x-1]==' ') n[x]-='a'-'A';
else if(n[x]>='A' && n[x]<='Z') n[x]+='a'-'A';
}
}

cout<<n<<endl;

hey..i have tries the while loop...but it doesnt works...can ne1 spot the prblm

int main(int argc, char *argv[])
{
    string n;
    string s;
 
 {   

  cout<<"Please enter your name :"<<flush;
  getline(cin, n);
  
  for(int i=1; i<n.length(); i++)
  while(n[i]<='A'|| n[i]>='z');
  
  cout<<"Error code 01: Name contains a character that is neither an alphabet nor a space"<<endl;
  cout<<"Please enter your name :"<<flush;
  getline(cin, n);
   if(n[0]>='a' && n[0]<='z') n[0]-='a'-'A';


   for(int x=1; x<n.length(); x++)
   {
            if(n[x]>='a' && n[x]<='z' && n[x-1]==' ') n[x]-='a'-'A';
             else if(n[x]>='A' && n[x]<='Z') n[x]+='a'-'A';
  }

 cout<<n<<endl;

}

Sorry, I didn't test it before. This does work:

#include <iostream>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
    string n;
    //Removed string s; it wasn't being used...?
    bool Error = true;
    
    //Main loop added
    while(Error)
    {
        Error = false;
        cout<<"Please enter your name: "<<flush;
        getline(cin, n);

        for(int i=0; i<n.length(); i++)
            //Checking for whitespace added, your version gave an error on space
            if(n[i] != ' ' && (n[i] <= 'A' || n[i] >= 'z'))
            {
                cout<<"Error code 01: Name contains a character that is neither an alphabet nor a space"<<endl;
                Error = true;
                break;
            }

        //Only convert if the input is correct
        if(!Error)
        {
            if(n[0]>='a' && n[0]<='z')
                n[0]-='a'-'A';

            for(int x=1; x<n.length(); x++)
            {
                if(n[x]>='a' && n[x]<='z' && n[x-1]==' ') n[x]-='a'-'A';
                else if(n[x]>='A' && n[x]<='Z') n[x]+='a'-'A';
            }

            cout<<n<<endl;
        }
    }

    return 0;
}

I changed/added a few things(Placed comments). Though I suggest you try structuring your code a bit better.
I'm not sure this is what you wanted, but it appears to be..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.