Home > OS >  how to loop through an array of string and turn them into ascii , while storing them in dynamic memo
how to loop through an array of string and turn them into ascii , while storing them in dynamic memo

Time:08-26

i am trying to make a program that turns each character of a string into an ascii character and store them into an array and then print them out . However it doesn't allow me to print anything out . I have tried assigning a string to the message input and it works perfectly but it doesn't work for user input.It just ends the program and i am not receiving any errors so i don't know whats wrong with my program(c 11).

using namespace std;

string message_input{};
        int l = message_input.length();
        double* ascii_storage = new double[l  1]{};
        
        cout << "type in your message  " << endl;

        std::getline(std::cin, message_input);

        

        for (int i = 0; i < l;   i) {
            ascii_storage[i] = (int)message_input[i];

            cout << "the values inside the ascii baskii " << ascii_storage[i] << endl;
        }

CodePudding user response:

string message_input{};

This defines a new std::string. The string is empty, by default.

int l = message_input.length();

This obtains the string's length(). The string is empty, so l must be 0 at this point.

std::getline(std::cin, message_input);

This now reads some input, of unspecified length, from std::cin. message_input is now a string of some unspecified length.

The subsequent code clearly assumes that l gets automatically updated to the string's new length. However, C does not work this way, C does not work like a spreadsheet does. l is still 0, and will be 0 forever, in the shown code.

You must use length() or size() after reading the input from std::cin, not before.

  • Related