0
#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?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
user2027369
  • 63
  • 1
  • 7

2 Answers2

1

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.)

Community
  • 1
  • 1
0

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.

voidMainReturn
  • 3,339
  • 6
  • 38
  • 66