Problem with spaces

the program is supposed to ask the user for the length of what they wish to type and the program would recive it as an array then make all the letters to uppercase then out put the array with all caps and all spaces

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
ude <iostream>
#include <ctype.h>
#include <string.h>

using namespace std;
int length;
char *str;
int main ()
{
    
    cout<<"Enter the length of the string please : ";
    cin>>length;
    
    str = new char[length];
    
    cout<<"Enter the string: ";
    cin.getline(str,length);
    
    for(int i = 0; i < strlen(str); i++)
       str[i] = toupper(str[i]);
   cout <<endl << str << endl;
    
    system ("pause > NULL");
    
}
I am just looking for a hint i will admit this is homework but i'm not understanding the problem with the program as i've searched online ,in the archives, and have tried to fix it many different ways.
statements such as cin >> length should be followed with a call to cin.ignore() to remove the newline from the input stream.
Or alternatively you could use std::string and get rid of providing expicit length.
MiiNiPaa it has to be an array saddly. i would love to use string and be done with it.

Yanson your help almost compleatly fixed the problem, when i enter the int for length say 8 and then for the string type "what what" it prints "WHAT WH"

any idea on why or a way to solve this?
well, it does read 7 characters + 1 for terminating 0 = 8, as you specified. For "what what" string you need 10 characters at least.
this is going to sound dumb but why is that? w(1)h(2)a(3)t(4) (5)w(6)h(7)a(8)t(9) why wouldn't it be 9? i need to take my time when counting... thinking it would be 8.
Do not forget about terminating 0 which should ne included in array size.
String "what what" actually looks like:
 w   h   a   t   _   w   h   a   t  \0
119 104  97 116  32 119 104  97 116  0


So you either have to pass 10 as size of said string or pass 9 and use
str = new char[length + 1];
Last edited on
So what would be a way to make it so it always comes out right? no matter the length?
What do you mean by "always correct"? I pointed out how c-string are working. If you want to get rid of length, you need to use dynamic storage, like std::string, or make something similar.
ooo ok well in that case thank you so much for your help and explaining :)
Topic archived. No new replies allowed.