how to capitalize the letter after a space in an array?

closed account (Ez7GNwbp)
hello!

I've been struggling with this code for quite a while now.
the assignment is to read a data file with a list of names, capitalize the first character of the first and last name by making an array and subtracting 32 from the character, and then outputting the names onto the screen.

so far i have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
    string line;
    ifstream myfile ("Names.txt");
    if (myfile.is_open())
    {
        while ( myfile.good() )
        {
            getline (myfile,line);
            
            string str = line;
            
            str[0] = str[0] - 32;
      
            cout << str << endl;
            
        }
        
        
        myfile.close();
        
    }
    
    return 0;
}


this allows me to read a name, and capitalize the first letter of the first name. however, I cannot figure out how to capitalize the first letter of the last name. please help!!
Split line into tokens:
http://www.cplusplus.com/search.do?q=string+tokens
with ' ' (space) as delimiter.

If structure of the file is fixed you can use std::string::find() to find space char and change 1 char after it but that wouldn't be as nice as token solution.
Last edited on
Try this:
1. Check if the first token is the first letter in the line. If it is capitalize it.
2. Check if the token is empty ' '. If it is, capitalize the next token.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
    #include<iostream>
    using namespace std;
    
    int main()
        {
          string line = "david johnson";
          int len = line.size();
          for(int i = 0; i < len; i++)
            {
              if(i == 0 && line[0] != ' ')
                {
                  line[0] = (int)line[0] - 32;      
                }
              else
                  if(line[i] == ' ')
                    {
                      line[i+1] = (int)line[i+1] - 32;      
                    }      
            }
          
          cout << line << endl;
          
          system("pause");
          return 0;      
        }
Last edited on
Topic archived. No new replies allowed.