Why does this work w/out header files?

Pages: 12
LOL, it compiles and runs here, but I am getting garbage chars at the end of long input?? Should I try to force my entire string to upper, then copy it into the dynamic array, and then just print the dynamic array? I am sooo close and want to get on w/ my day.

Thanks,
Brent
gcampton wrote:
I still don't get it, how does string str1; work without include <string> using gcc
you didn't read the link i post..
http://cplusplus.com/forum/beginner/18613/#msg95508

gcampton wrote:
how did blackcoder41 know the code compiled correctly ?
telepathy! LOL ^^
@brentsid
upload an image of your output here http://imageshack.us/.. let me see what you getting there.
Last edited on
I'm sorry, my bad, I forgot the terminating binary null which is required for c-strings to work.
The correct code is
1
2
3
4
std::string str = "lowercase string";
char *cstr = new char[32];
*std::transform(str.begin(), str.end(), cstr, &toupper) = 0;
std::cout << cstr;
Last edited on
Well I solved my own problem eventually. I had a problem with the array size, which adds an extra garbage char. Here is the working code. I changed size+1 to size for the dynamic array size and one of my for loops was stopping at last instead of size. With these two logical errors fixed it now works. Thansk all for the above help but it is way over my head so I will use my caveman version>

Brent

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
/* 
BRENT SMITH -- UNIT 3 PROGRAMMING ASSIGNMENT

Using dynamic arrays, Write a program that prompts the user to input a string
and outputs the string in uppercase letters. 
(use a char array to store the string.)
*/

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str1;
    int size;
    cout <<"Enter a sentence to be forced to upper case" <<endl;
    getline (cin, str1);
    size = str1.length();

    char *str2 = new (nothrow) char[size+1]; //char pointer called str2 // remeber to add room for terminal char.
    if(str2 == NULL) //feeble error checking attempt
    {
       cout <<"Unable to allocate memory." <<endl;            
    }
   
    //deep copy str1 into *str2
    for(int i = 0; i < str1.length(); i++ )
    {
      str2[i] = str1[i];  
    }
    int last = (size); //one past last char is where I want my deliminator
    str2[last] = 0; //add deliminating char to dynamic array
     
      //loop through dynamic array whatever size it may be
      for(int i = 0; i < size; i++ )
      {
         if(isalpha(str2[i]))//if element is alphabetic
         {
          str2[i] = toupper(str2[i]); //capitalize whole array if need be
         }    
      }
     
    cout << str2 << endl;  
    delete[] str2; //deallocate dynamic array memory
   
    system("PAUSE");
    return 0;
}// end main 
Topic archived. No new replies allowed.
Pages: 12