Extracting from Input and Writing to Output.

One of our recent LAB assignments was to take some provided input files and use them to create complete C++ Programs. The second one of which gave me a bit of trouble.

What you're supposed to do with this program is extract a message from an input file and write it to an output in all uppercase letters. However, after creating the program, the first iteration only wrote a capital "O" to the output file, and after some tweaking, more letters were written, the problem is the output was little more than random letters from the message.

This is my code below.

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <fstream>
#include <cstdlib>
#include <string>
#include <iostream>
#include <cctype>
using namespace::std;


void main()
{

  ifstream input;
  ofstream writing;


  writing.open("c:\\temp\\upper.txt");
if (!writing)
{
  cout << "Opening of output file failed.\n";
  return;
}
  input.open("c:\\temp\\message.txt");
if (!input)
{
  cout << "Opening of input file failed.\n";
  return;
}

  char type;
    
  while(input >> type)
  {
    input.get(type);

    if(static_cast<char>(isupper(type)))
    {
      writing << type;
    }
      if (static_cast<char>(islower(type)))
     {
       writing << static_cast<char>(toupper(type));
     }
       if(static_cast<char>(isspace(type)))
       {
         writing << type;
       }
  }
    writing.close();
    input.close();

    return;
}


The message read from the input file is:

Today Steve Rountree ate 1 apple and 2 eggs.'

The output file is supposed to have the same message, except in all caps. Yet when run and the file is viewed, it comes out as random capital letters in sequence from the message. I get the feeling I'm doing something wrong here that I'm not seeing. Does anyone know what it is?
1
2
3
 while(input >> type)
  {
    input.get(type);
Why are you reading 2 times?
Also, you don't need to check the letters before send them to toupper

main must return int
Last edited on
static_cast is good, but you might also look at transform.
Topic archived. No new replies allowed.