Filling a character array with a string.

I need to fill an array with a string that is input by a user. I think I need to use a dynamic array, but I'm not even sure about that. Here is the code I have so far:

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
#include <iostream>
#include <string>
#include <cstring>


using namespace std;

void initializeArray(char list[], int listSize);

void printArray(char list[], int listSize);

int main()
{
    string line;

    cout << "Enter a string" << endl;
    getline(cin, line);
    cout << line << endl;
    cout << line.length() << endl;

    char *lineToProcess;
    int arraySize = line.length();

    lineToProcess = new char[arraySize];

    initializeArray(lineToProcess, arraySize);

    printArray(lineToProcess, arraySize);

    return 0;
}

void initializeArray(char list[], int listSize)
{
    int index;

    for (index = 0; index < listSize; index++)
            {
                list[index] = 'A';
            }
}

void printArray(char list[], int listSize)
{
    int index;

    for (index = 0; index < listSize; index++)
        cout << list[index];
}


I am not sure if I have the dynamic array set up properly, and if I do, I am at a complete loss for how to get the string variable line to copy into the array. I have tried everything that I can think of, but I havent been able to come up with a solution that works.
Right now you are building a bus and filling the seats with 'A', and doing nothing with the string you created. Pass it in and fill the array

void initializeArray(string ,char[], int);

1
2
3
4
5
6
7
8
9
void initializeArray(string str, char list[], int listSize)
{
	int index;

	for (index = 0; index < listSize; index++)
	{
		list[index] = str.at(index);
	}
}

Thank you, I will try that. What does the string.at(index) function do? I haven't seen that yet.
Never mind, I looked it up, and it looks like it works beautifully. Thank you for the help!
> I need to fill an array with a string that is input by a user. I think I need to use a dynamic array

std::string is a dynamically resizeable array of characters.

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
#include <iostream>
#include <string>
#include <cstring>

// using namespace std;

int main()
{
    std::string line;

    std::cout << "Enter a string" << '\n' ; // endl;
    std::getline( std::cin, line );
    std::cout << line << '\n';
    std::cout << line.length() << '\n' ; // endl;

    //char *lineToProcess;
    //int arraySize = line.length();
    //lineToProcess = new char[arraySize];
    // initializeArray(lineToProcess, arraySize);

    // initialize lineToProcess as a string of the same size,
    // filled with the character 'A'
    std::string lineToProcess( line.size(), 'A' ) ;

    // printArray(lineToProcess, arraySize);

    // print it out as a sequence of characters
    std::cout << lineToProcess << '\n' ;

    // print it out character by character
    for( std::size_t i = 0 ; i < lineToProcess.size() ; ++i )
        std::cout << lineToProcess[i] ;
    std::cout << '\n' ;

    // print it out character by character, with a range-based loop this time
    for( char c : lineToProcess ) std::cout << c ;
    std::cout << '\n' ;

    //return 0;
}
I think we might be missing something here.

Why do you need to use an array when you already have a string? Did your instructor ask you to use arrays? (If so, you shouldn't be messing with the string?)

Otherwise, like JLBorges said, a string is an automatically managed array. Just do all your array stuff on the string.

Hope this helps.
I have only been at this for a few weeks, so I really just started with programming, but this is the first time I have been this stumped. The assignment is to complete a program that was started for us to do a caesar shift on an input file. I did not include the functions that just print headings etc. We were not given instructions on how to accomplish anything specifically, so I decided to use a dynamic array. Right now, it almost works, but it is going through each line of the input file multiple time and printing it to the output file. I think that my problem is somewhere in 135 to 178. I will put a copy of the output and input files next...

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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255

#include <iostream>
#include <fstream>
#include <sstream>
#include <cmath>
#include <ctime>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <cstring>

using namespace std;

//Constant Declarations
const int W_WIDTH = 80; ///< Width of the terminal window

//Forward Declarations - Function Prototypes

///
/// Utility Function to read a value from an input stream ( any type with a operator>> defined ) - non-interactive
///
template<class T>
bool readValue( istream &in_stream, T &value_in);

///
/// Utility Function to read a value from an input stream - interactive
///
template<class T>
bool readValue( istream &in_stream, T &value_in, string message, int width=34 );

///
/// Print a horizontal line
///
void printHorizontalLine( ostream& outs, char line_char, int width );

///
/// Print a centered heading
///
void printHeading( string title, int width );

///
/// Print the stylized program/project heading
///
void printProjectHeading( ostream& outs, int width );

///
/// Apply the caesar cipher
///
char caesarShift( char to_shift, int shift_value);

///
/// Print the encode and decode selection menu
///
void printMenu();

///
/// Read the shift value from the keyboard
///
int readShiftValue();

///
/// initiaize array to the contents of the line of input
///
void initializeArray(string str, char list[], int listSize);

///
/// Main Function
///
int main(){
    fstream in_file;            ///< Input File Stream
    fstream out_file;           ///< Output File Stream

    string input_filename;      ///< Input File Name
    string output_filename;     ///< Output File Name

    string line;                ///< String to store each line

    int shift_value;            ///< Shift Value for caesar Cipher

    char choice       = '\0';   ///< User menu selection
    char current_char = '\0';   ///< Current character to be processed

    //Print the program heading
    printProjectHeading( cout, W_WIDTH);

    // Read the input and output file names
    readValue( cin, input_filename,  "Read from which file? ");
    readValue( cin, output_filename, "Write to which file? ");

    //Open the filestreams
    in_file.open( input_filename.c_str(), ios::in );
    out_file.open( output_filename.c_str(), ios::out );

    //Validate the filestreams
    if( in_file.fail() ){
        cerr << "Input file is invalid.\n";
        return 1;
    }

    if( out_file.fail() ){
        cerr << "Output file is invalid.\n";
        return 2;
    }

    //Read the Shift "Key" Value
    shift_value = readShiftValue( );

    //Display the Encode Decode Selection Menu
    printMenu();

    //Read the User Selection and convert to uppercasei
    readValue( cin, choice, "Select an Option: " );
    choice = toupper( choice );

    // validate the user choice, if invalid exit the program

    if (choice != 'D' && choice != 'E' )
    {
        cerr << "\n\n**********************************" << endl
             << "ERROR!   ERROR!   ERROR!   ERROR! " << endl
             << "**********************************" << endl;

        cerr << "\nYou have made an invalid choice!" << endl
             << "The program will now terminate." << endl;

        return 3;
    }
    if( choice == 'D' ){
        shift_value = -1 * ( shift_value );
    }


    //read each line of the file
    while(  !in_file.eof() ){
        //Read the line
        getline( in_file, line );

        //Iterate through each character in the line string
        for( int i = 0; i < line.length(); i++ ){
            //Retrieve the i-th character from the string
            //MODIFY the following line
            //Hint: array subscripts - line[ some # ]
            char *lineToProcess;                                //declare pointer
            int arraySize = line.length();                      //declare dynamic array size variable equal to length of string

            lineToProcess = new char[arraySize];                //declare dynamic array and assign to pointer

            initializeArray(line, lineToProcess, arraySize);    //initialize array with contents of string line            

            for (int a = 0; a < arraySize; a++)                 //assign each character of array to current char and perform encode/decode
            {
               current_char = lineToProcess[a];                 //assigns array index to current char

            //Convert the line to uppercase
               current_char = toupper( current_char );

            //If the character is in the range A to Z, apply the caesar shift
            //otherwise output the character unmodified
                if( current_char >= 'A' && current_char <= 'Z' ){
                    out_file << caesarShift( current_char, shift_value );
                }
                else{
                    out_file << current_char;
                }

            }// end for

        delete [] lineToProcess;            // delete dynamic array

        }// end for

        //If the current line is not the last, output a newline character
        // MODIFY - Do not output an extra newline at the end of the file
        out_file << "\n";


    }//end while

    //Close the input and output files
    in_file.close();
    out_file.close();

}

///
///
///
template<class T>
bool readValue( istream &in_stream, T &value_in){
     in_stream >> value_in;

     //Return False on read error
     return in_stream.good();
}

///
///
///
template<class T>
bool readValue( istream &in_stream, T &value_in, string message, int width ){
     cout << left << setw( width ) << message << ": ";

     return readValue( in_stream, value_in );
}

///
/// Function to read and verify the shift value
///
int readShiftValue(){
    int shift_value = 0;

    while (shift_value < 1 || shift_value > 25)     //validate the shift value until a correct value is entered
    {
        readValue( cin, shift_value, "Enter a shift value between 1 and 25: "); //Read the value
    }

    return shift_value;
}

///
/// Function to encode or decode the file
///
char caesarShift( char to_shift, int shift_value){
    char result_char;  ///< resulting char

    //Replace the following line with the shift code
    if (to_shift == 'Z'  && shift_value >= 0)
    {
        result_char = 'A';
    }
    else if (to_shift = 'A' && shift_value <= 0)
    {
        result_char = 'Z';
    }
    else
    {
        result_char = to_shift + shift_value;
    }

    return result_char;
}

///
/// Function to initializr dynamic array with the contents of line
///
void initializeArray(string str, char list[], int listSize)
{
    int index;

    for (index = 0; index < listSize; index++)
            {
                list[index] = str.at(index);
            }
}
Input:

********************************************************************************
Thomas Kennedy
07 October 2013
P2-Solution-2.cpp
Integer Classification
********************************************************************************
--------------------------------------------------------------------------------
# Integers | Even | Zero | Odd | Odd/Even
--------------------------------------------------------------------------------
20 | 9 | 2 | 11 | 1.222
7 | 6 | 2 | 1 | 0.167
20 | 9 | 2 | 11 | 1.222


File: P2-input1.txt Compiled By: Steve Miller

P2-input2.txt Johnny FokkerTriPlane
P2-input1.txt Steve Miller


Thank you for using the Integer Classification utility.
update: When I run the program now it put out complete nonsense...
I dont know what is going on. I changed the out_file to cout in line 161 and 164 to see what was going on and it ran for almost minute before it finished and it just put out a bunch of * and what looks like wingdings, over and over...
You've made a few beginner's mistakes. A few of them are easily caught if you set your compiler to complain about everything.

Line 232: Use else if (to_shift == 'A' && shift_value <= 0)
(Notice the '=='.)

Lines 135 & 137: should be combined.
while(getline( in_file, line )){
Don't loop on EOF. It is almost always the wrong thing to do.
You should loop on whether or not the last attempt to read the file succeeded, which the new loop does.

Lines 140 & 167: Don't do that. It is causing your output to duplicate (or repeat) once for the length of each input line.

For example, given input:
why
hello!

If you were to not Caesar-shift anything, your output would be:
whywhywhy
hello!hello!hello!hello!hello!hello!


There's still a bug in your program, but I'll let you work on it a bit from there.

Hope this helps.
Thank you for the input, I appreciate you not just giving a solution, I am really trying to understand this stuff and work it out on my own. I will implement your suggestions and keep working on it. Thank you again!
Topic archived. No new replies allowed.