-4

So I'm trying to have the user enter strings that will be put into an array with the maximum size of 50 strings. Whenever the user enters "stop", I want the loop to stop and the array to cutoff there.

I then want to read the array back to the user. I tried running this and got a really weird error. Can someone explain to me why this doesn't work and how I would fix it? Thanks.

int main(int argc, const char * argv[]){

    string array[50];

    // Get's inputs for array
    for(int i = 0; i < 50; i++){
        cout << "Enter string: ";
        getline(cin, array[i]);

        if(array[i]== "stop"){
            array[i] = "\0";
            break;
        }

     }

    // Reads inputs from array
    for(int i = 0; i < sizeof(array); i++){
        cout << array[i] << "\n";
    }

    return 0;


}

I don't know why I'm getting down voted so hard?

Suds2
  • 241
  • 2
  • 5
  • 14

3 Answers3

3

Use std::vector for your task. It has the method push_back() where you can add elements dynamically. Also you can check the size of the vector easily by calling vector.size().

int main(int argc, const char * argv[]){

    vector<std::string> array;

    // Get's inputs for array
    for(int i = 0; i < 50; i++){
        cout << "Enter string: ";
        string line;
        std::getline(cin, line);
        array.push_back(line);

        if(array[i]== "stop"){
            array[i] = "\0";
            break;
        }

     }

    // Reads inputs from array
    for(int i = 0; i < array.size(); i++){
        cout << array[i] << "\n";
    }

    return 0;
}

In your code you would have to implement a counter that counts, how many inputs the user did.

kylecorver
  • 449
  • 1
  • 4
  • 12
0

Normally you would use vectors, but since you have not reached that section of the book, I guess they want you to solve it with C-style arrays.

You can get the length of a C-style array like this

int size = (sizeof(array)/sizeof(*array)

But since you know the maximum number of entries are 50 and that you must stop when you reach the word stop, maybe you rather want this

for(int i = 0; i < 50; i++){
    if (array[i] == '\0')
        break;
    cout << array[i] << "\n";
}
Leon
  • 12,013
  • 5
  • 36
  • 59
-2

I just implemented a loop to find out how long the array is.

// Determines how long the array is
    for(int i = 0; i < 50; i++){

        if(array[i] == "\0"){
            break;
        }

        counter++;
    }
Suds2
  • 241
  • 2
  • 5
  • 14