Hi all, I am new in C++ programming. I am building a program where I have to take input for many variables. Some variables are single integers and some are array of integers. A sample input text file is like this:
4 /* Number of rows, I want to store in int variable "N" */
5 /* Number of columns, I want to store in variable "X" */
20 40 20 25 30
20 30 40 20 25
20 40 20 25 30
20 30 40 20 25 /* array of N rows and X column , i want to store in A(N,X) */
When you read in the first number, that will be the number of rows, hence the number of arrays you will need. So you read in 4, then you do:
arr = newint *[4];//Pointer to 4 spaces in memory or 4 arrays of undetermined sizes.
1 2
//First for-loop starts here:
for (int x = 0; x < 4; ++x)
Next you will read the 5, this will be your number of columns hence number of items to be contained in each array. So the next line after the for-loop should be:
arr[x] = newint[5];//Now you have given that array a size and now you can start storing the values in it.
1 2
//Second for-loop starts here
for(int i = 0; i < 5; ++i)
Now to store values in the arrays you have created, you do:
However, my data is in text file. So how i will read my data from text file. I have read input/output document. I was trying to use getline command, but the problem is how to store the data from text file into my variables.
For eg. i have to read that number of rows are 4 and then store the value in variable "N" so that i can define
arr = new int *[N]; instead of arr = new int *[4];
actually 4 is just a number , it can be any integer.
Reading in the values from the text file is as easy as reading it in from a user. There are 3 ways:
Using input/output redirection <, having program open and read from a file using ifstream(c++) or FILE* (c), or using the text file as arguement when running the program(you've probably seen int main(int argc, char **argv)) argc is number of arguements, argv is an array of arguements