99.0k views
4 votes
What's the problem with this code ?

Note: I have to write a piece of code where the first input is the number of cases and afterwards names are entered, seperated by a new line, a name can have at most three parts: first name, middle name and last name. It will have at least one part. The last name is always present. The rules of formatting a name are:

*Only the first letter of each part of the name should be capital.
*All the parts of the name except the last part should be represented by only two characters. The first character should be the first letter of the part and should be capitalized. The second character should be ".".

'#include
#include
#include
#include

using namespace std;

int main()
{
short T;
cin >> T;

string str[100];

//cin.clear();
//cin.sync();
cin.ignore(); //or getchar();

short i = T;
while(T--)
{
getline(cin, str[T-1]);
cin.ignore();
}

stringstream ss(str[i-1]);
string tmp;
//vector v;

short j;
while(i--)
{
j = 0;
while(ss >> tmp)
{
if(j >= 2)
{
tmp[0] = toupper(tmp[0]);
cout << tmp << ends;
}
else
{
tmp = toupper(tmp[0]);
cout << tmp << "." << ends;
j++;
}
}
cout << endl;
ss << str[i-1];
}


return 0;
}
'

User Varren
by
7.4k points

1 Answer

4 votes
Hi,

I changed your program using some of the concepts you were trying to use. Hopefully you can see how it works:

#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
short T;
cin >> T;
cin.ignore();

string str[100];

for(int i=0; i<T; i++)
{
getline(cin, str[i]);
}

for (int i = 0; i < T; i++)
{
stringstream ss(str[i]);
string tmp;
vector<string> v;

while (ss >> tmp)
{
// Let's capitalize it before storing in the vector
if (!tmp.empty())
{
transform(begin(tmp), end(tmp), std::begin(tmp), ::tolower);
tmp[0] = toupper(tmp[0]);
}
v.push_back(tmp);
}

if (v.size() == 1)
{
cout << v[0] << endl;
}
else if (v.size() == 2)
{
cout << v[0][0] << ". " << v[1] << endl;
}
else
{
cout << v[0][0] << ". " << v[1][0] << ". " << v[2] << endl;
}
}

return 0;
}

User James Roland
by
7.1k points