I need to make a program that outputs a name based on the users input. For the middle name I'm only supposed to show the middle initial. But the way I have my code written causes an error.

#include<iomanip>
#include<iostream>
#include<string>

using namespace std;

string firstName;
string lastName;
string middleName;
string middleInitial;

int main(){
	cout<<"Enter your first Name: "; cin>>firstName;
	cout<<"Enter your middle name or initial: "; cin>>middleName;
	cout<<"Enter your last name: "; cin>>lastName;
	cout<<"Your name is: "<<endl;
	for(int i=0; i<middleName.length; i++){
		middleInitial = middleName[1];
	}

	cout<<lastName <<", " <<firstName<<" " <<middleInitial <<endl;
}

what is the error??? Please don't make us guess.

You don't need a loop just to get the first letter of the string, so you can just delete lines 17, 18 and 29. cout<<lastName <<", " <<firstName<<" " <<middleName[0] <<endl;

>middleName.length
Length is a member function, not a data member. I'd also recommend using size() instead of length(), since length() is specific to the string class while size() is used in the standard container libraries.

Access first letter using index 0 not 1, but make sure user entered a middle name by checking size()

int main( int argc, char *argv[])
{
    std::string middle;
    std::cout<<"Enter your middle name: "; std::getline(std::cin,middle);

    if( middle.size() )
    {
        std::cout << "middle initial is=[" << middle[0]  << "]" << std::endl;
    }
    else
    {
        std::cout << "no middle name" << std::endl;
    }
}
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.