Dynamic arrays

I'm doing an exercise asking me to read an input of characters and to output the same characters in uppercase with dynamic arrays. My first code was this
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
#include <iostream>
#include <string>
#include <cctype>

using namespace std;

int main()
{
    string line;
    char *p;

    cout << "Enter your line: ";

    getline(cin, line);

    p = new char[line.length()];

    for(int i=0; i<line.length(); i++)
    {
        p[i] = line[i];
        cout << static_cast<char>(toupper(p[i]));
    }

    return 0;
}


but I think it's a bad algorithm because it first reads the string to calculate the dimension of the array to create and then gives the right values to the array. Is there a method to use just the array saving time and calculation?
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
#include <iostream>
#include <string>

int main()
{
	/*Read input*/
	std::string word;
	std::cout << "Enter a word written in lower case:";
	std::cin >>word;

	/*Set up dynamic array*/
	int size = word.size();
	int *A = new int[size];
	
	/*lower case to upper case*/
	for(int i=0; i<size; ++i)
	{
		A[i] = word[i] - 32;
	}
	for(int j=0; j<size; ++j)
	{
		word[j] = A[j];
	}
  
	/*Print result*/
	std::cout << word << std::endl;
}



didn't really know where else to use the dynamic array. but solves the task i guess.
I didn't get the "A[i] = word[i] - 32;" part. Anyway the problem persist because you read characters through a string while I want to read data directly using the array
that -32 is simply a shift in the ascii table. google ascii and have a look, if you dont get it.
Sure, my bad!
Topic archived. No new replies allowed.