Home > Enterprise >  Input information into a string array - overwriting other parts?
Input information into a string array - overwriting other parts?

Time:11-11

I have a string array that I would like to hold information input at runtime. I'm using an int var to control how many 'rows' there are in my array, but there will only ever be a set number of 'columns'.

#include <iostream>
using namespace std;

int main() {
    int rows;
    cout << "How many rows? ";
    cin >> rows;
    
    string data[rows][2];
    
    for(int i = 0; i < rows; i  )
    {
        cout << "Column 1: ";
        cin >> data[i][0];
        
        cout << "Column 2: ";
        cin >> data[i][1];
        
        cout << "Column 3: ";
        cin >> data[i][2];
    }
    
    for(int i = 0; i < rows; i  )
    {
        cout << "Row " << i 1 << endl;
        cout << "Column 1: " << data[i][0] << endl;
        cout << "Column 2: " << data[i][1] << endl;
        cout << "Column 3: " << data[i][2] << endl;
    }
}

Expected output: Row 1 Data 1: 123 Data 2: 456 Data 3: 789 Row 2 Data 1: aaa Data 2: bbb Data 3: dcc

Actual output: Row 1 Data 1: 123 Data 2: 456 Data 3: aaa Row 2 Data 1: aaa Data 2: bbb Data 3: dcc

This works for entering a single row, but if I'm entering more than one rows worth of data at a time, the last column's data is overwritten by the first column's data for the next row (so [0][2] holds the same data as [1][0]).

(Unfortunately, I am very new at C so can't figure out what's going on :()

CodePudding user response:

Well, if I understood correctly that the task is to store strings with text in an array that imply the use of newline hyphenation, then here:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
    int rows;
    cout << "How many rows? ";
    cin >> rows;

    vector <string> page;

    for (int i = 0; i < rows; i  )
    {
        string temp;
        cout << "Column 1: ";
        cin >> temp;
        page.push_back(temp);

        //test 
        temp = "Column: \n Column:2";
        page.push_back(temp);
        //end test

        cout << "Column 3: ";
        cin >> temp;
        page.push_back(temp);
    }

    for (auto & item : page)
    {
        cout << "\n page = {\n" << item<<"}\n";
    }
}

and yes, in a static array, you cannot specify its variable size, since the value of the variable is not known during compilation, which is why the maximum possible amount of memory is allocated for the array

  • Related