user2027369
user2027369

Reputation: 63

Trying to find the middle initial of a name

#include<iostream>

using namespace std;

int main(){
    char sampleName[30];
    char middle;
    int i;

    cin>>sampleName;

    for(i=0;i<30;i++){
        if(sampleName[i]=='.'){
            middle=sampleName[i-1];
            break;
        }          
    }

    cout<<middle;

    return 0;
    }

It doesn't seem to work though when the input has spaces in it. Please. Can anyone help me out?

Upvotes: 0

Views: 746

Answers (2)

voidMainReturn
voidMainReturn

Reputation: 3517

you hav getline function to get in a line with spaces. You are getting wrong output because your program is not taking input with spaces correctly.

Upvotes: 0

user2530166
user2530166

Reputation:

I am not completely sure what your expected input is, but you may wish to look into std::getline (in conjunction with std::string) to avoid whitespace issues with std::cin >> .... (See here for a relevant discussion.)

So, something of the form

#include <iostream>
#include <string>

int main()
{
    std::string sampleName;
    char middle;

    std::getline(std::cin, sampleName);

    for (int i = 0; i < sampleName.size(); i++)
    {
        if (sampleName[i] == '.')
        {
            middle = sampleName[i-1];
            break;
        }          
    }

    std::cout << middle << std::endl;

    return 0;
}

may work best. (Click here to test.)

Upvotes: 1

Related Questions