0

I'm trying to make an array that hold multiple user input strings, I've tired structs and dynamic arrays and it does not work

I tried making a struct that holds a string, and tried making array of struct and it didn't work

#include <iostream>
#include <string>
#include <limits>



using namespace std;

int main()
{
    int rows;
    cin >> rows;
    string **arr = new string*[rows];
    for( int i = 0; i < rows; ++i)
    {
        arr[i]= new string[1];
    }
    for(int i = 0; i < rows; ++i)
    {
        getline(cin, arr[i][0]);
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }


    for(int i = 0; i < rows; ++i)
    {
        cout << arr[i][0] << '\n';
    }


    for( int i = 0; i < rows; ++i)
    {
        delete [] arr[i];
    }
    delete [] arr;
return 0;
}

it allows rows + 1 inputs then crashes

3
  • 3
    why don't you use vectors? Commented Jul 30, 2019 at 6:59
  • 3
    prefer std::vector<std::string>. Commented Jul 30, 2019 at 6:59
  • 1
    The second level of indirection here is worthless. If you really want to use a dynamic sequence of std::string, you should use std::vector<std::string> as stated earlier. For this code, however, arr should be std::string *arr = new std::string[rows];, all referrals to arr[i][0] should be simply arr[i], and the last for loop should be completely thrown out. Commented Jul 30, 2019 at 7:08

2 Answers 2

4

Use std::vector and std:string types to easily get the job done:

#include <iostream>
#include <string>
#include <limits>
#include <vector>

using namespace std;

int main()
{
    int rows;
    cin >> rows;
    std::vector<std::string> vec;
    std::string s;

    // flush cin
    std::getline(std::cin, s);


    for (int i = 0; i < rows; ++i)
    {
        std::getline(std::cin, s);
        vec.push_back(s);
    }


    for (int i = 0; i < rows; ++i)
    {
        cout << vec[i] << '\n';
    }

    return 0;
}
Sign up to request clarification or add additional context in comments.

2 Comments

@WhozCraig correct, modified accordingly. Thank you!
@JackWilliam great, then you may mark my answer as best answer for this question.
0
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');

should be done in case of error, not in regular cases.

Demo

2 Comments

This doesn't answer OP:s question at all, does it?
@TedLyngmo: I doesn't reproduce the "crash", but incorrect output, with provided fix, I got expected result (as shown in Demo). So even if OP style is bad, I don't see UB or similar.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.