Search code examples
c++debugginggarbage

Why I am getting a garbage value after entering number of test cases in the first line of the input?


Input:

The first line of the input contains an integer T denoting the number of test cases.

The only line of each test case contains the space separated parts of the name.

Output

For each case, output the properly formatted name.

Constraints:

  • 1 ≤ T ≤ 100
  • 2 ≤ Length of each part of the name ≤ 10 Each part of the name contains the letters from lower and upper case English alphabets (i.e. from 'a' to 'z', or 'A' to 'Z')

    ***Input***
    3
    gandhi
    mahatama gandhi
    mohandas karamchand gandhi
    
    
    ***Expected Output:***
    Gandhi
    M.Gandhi
    M.K.Gandhi
    
    
    ***My output:***
    à
    Gandhi
    M.Gandhi
    M.K.Gandhi
    

Why am I getting the "à" symbol in the first line? I have created a function formatter to provide a for loop for the testcases.

I apologize in advance if the code is too clunky.

#include<bits/stdc++.h>
using namespace std;
int z;
void formatter(int z){
  for(int q = 0;q <= z;q++){
  string s;
  int count=0;
  int k = 0,p = 0,r = 0,t = 0,l = 0,a = 0,x = 0 ;
  getline(cin,s);
  for(int p = 0;p <= s.size();p++){
    if((s[p]==' ')||(p==0)){
       count++;
       }
  }
  if(count == 1){
    while(r<=s.size()){
    s[0] = s[0] -'a' + 'A';
        cout << s[r] ;
    r++;
  }
   cout << "\n";
  }
  if(count == 2){
    for(int l = 0;l<s.size();l++){
          if(l==0){
             s[l] = s[l] -'a' + 'A';
             cout << s[l] << ".";
             a++;
          }
          if(s[l]==' '){
          if(a==1){
            ++l;
            while(l <= s.size()){
            if(x == 0){
            s[l] = s[l] -'a' + 'A';
          }
            cout << s[l] ;
            a++;
            l++;
            x++;
          }
    }
  }
 }
            cout << "\n";
}
  if(count==3){
  for(int i=0;i<s.size();i++){
        if(i==0){
                s[i] = s[i] -'a' + 'A';
        cout << s[i] << ".";
        t++;
        }
    if(s[i]==' '){
    if(t==1){
        ++i;
        s[i] = s[i] -'a' + 'A';
        cout << s[i] << ".";
        t++;
    }
    else
    while(k<=10){
    if(k==1){
    s[i] = s[i] -'a' + 'A';
    }
        cout << s[i];
        i++;
        k++;
    }
    }


  }
}


}
 cout << "\n";
}
int main(){
  cin >> z;
  formatter(z);
 }

Solution

  • A few things

    • The cin that reads the count in main does not consume the endline
    • The loop in formatter is from 0 to the number read in main, inclusive. This is wrong.
    • Consider toupper to convert to uppper case.
    • Consider factorizing the code that handles 1, 2 and 3 names.