I want to read a file into an int array , but I need to do that one element at a time.
Here's what's in the file :
1000320
0110313
3333000
2033000
2203011
2000010
And here is the code :
std::ifstream fin("file.in");
for (int i=0; i<6; ++i) //rows
{
for (int j=0; j<7; ++j) //columns
{
fin>>_array[i][j];
}
}
If I would print _array[0][0] it will output everything that's on the first line. However I want to split what's in the file into rows and columns .
What's the most elegant way to do this for an INT array ( I don't want to use a char array although it would be much easier . Also , I know that if I put spaces between the numbers in my file the program would read them one at a time but I want them to be like this )
You can try using getchar()
You'll get char but just convert it to int immediately
char temp = getchar(fin);
_array[i][j] = temp - '0';
Unfortunately there's no getint()
in case you want to keep the same structure
#include<fstream>
int main() {
int n;
fstream fin("urfile.txt");
string line;
int _array[6][7];
for (int i = 0; i < 6; ++i) //rows
{
std::getline(read, fin);
for (int j = 0; j < 7; ++j) //columns
{
_array[i][j] = line[j]-'0';
cout << _array[i][j];
}
cout << '\n';
}
fin.close();
}
Related
I am a newcomer to C++. need to write a piece of code in C++, read the txt data, expand into one dimension (one row or one column) and sort in descending order. Finally I want to specify a percentage range to average. I found some code snippets on the web and debugged it like this, but in the sorting phase I can't get the results I want, all the data will be turned into -858993460. Hope someone can help me.
txtfile
#include "stdafx.h"
#include <vector>
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<fstream>
#include<typeinfo>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int i = 0, j = 0, k = 0;
int t = 0, f = 0;
int data[20];
ifstream infile;
infile.open("C:\\Users\n\Desktop\1111.txt");
for ( i = 0; i < 5; i++)
{
for ( j = 0; j < 4; j++)
{
infile >> data[k++];
}
}
for (i = 0; i < 5; i++)
{
for (j = 0; j < 4; j++)
{
if (data[i] > data[j]) //Sort from big to small
{
//Exchange the values of both
t = data[i];
data[i] = data[j];
data[j] = t;
}
}
}
for (int f = 0; f < 20; f++)
{
cout << data[f];
cout << '\n';
}
system("PAUSE");
}
result
You need to escape your
\
If you change your
infile.open("C:\\Users\n\Desktop\1111.txt");
to
infile.open("C:\\Users\\n\\Desktop\\1111.txt"); it should work properly.
EDIT: I just reproduced your file and I can read all your inputs. I think there is still a problem with the opening process of your file.
Another problem: You read in 20 values into an array. Therefore you dont need 2 nested for loop. One loop which counts to 20 is enough to do that task. This is a main reason why your sorting algorithm wont work.
Some strange code but your main error is not checking that the file open has succeeded. The garbage values you are getting strongly suggests that the file open has failed.
Files can fail to open for lots of reasons (include the one that cKai mentioned above). Add the following to your code to check if the file has opened.
ifstream infile;
infile.open("C:\\Users\\n\\Desktop\\1111.txt");
if (!infile.is_open())
{
cerr << "file open failed, quitting\n";
system("PAUSE");
return 1;
}
EDIT
OK so the above didn't prove anything, now maybe try this. Change
infile >> data[k++];
to this
if (!(infile >> data[k++]))
{
cerr << "read failed, quitting\n";
system("PAUSE");
return 1;
}
and see if that produces any error messages.
Intermittently, Visual Studio throws an exception when running my code. I say intermittently because I've been able to successfully run my code without an error. The error was thrown after I created the function "print_Days."
The exception thrown is:
Debug Assertion Failed!
File: minkernel\crts\ucrt\corecrt_internal_string_templates.h
Line: 81
Expression: (L"Buffer is too small" && 0)
The function reads from a .txt file that has 7 days of the week listed (Monday thru Sunday) and then alphabetically sorts the days in a 2D c-string array (professor is making us use c-string instead of string unfortunately).
Here is all of my code:
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
//Constants for 2D array
const int NUM_OF_ROWS = 7; //Seven days listed in the file
const int NUM_OF_COLS = 10; //Longest word is 9 chars long, plus \0
void get_Days(ifstream& file, char days[][NUM_OF_COLS], int rows);
void sort_Days(char days[][NUM_OF_COLS], int rows);
void print_Days(const char days[][NUM_OF_COLS], const int rows);
void get_Days(ifstream& file, char days[][NUM_OF_COLS], int rows) {
//Read from text file and return day
for (int i = 0; i < rows; ++i)
{
file >> days[i];
}
}
void sort_Days(char days[][NUM_OF_COLS], int rows) {
//Sort the array alphabetically
char temp[NUM_OF_COLS];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < rows; j++)
{
if (strcmp(days[j - 1], days[j]) > 0)
{
strcpy_s(temp, days[j - 1]);
strcpy_s(days[j - 1], days[j]);
strcpy_s(days[j], temp);
}
}
}
}
void print_Days(const char days[][NUM_OF_COLS], const int rows) {
//Print the sorted array to the console
for (int i = 0; i < NUM_OF_ROWS; ++i)
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < NUM_OF_COLS; j++)
{
cout << days[i][j] << endl;
}
}
}
int main() {
//This program reads from a file (days.txt), sorts the days
// alphabetically, and then prints the result to the console.
ifstream infile("days.txt");
char days[NUM_OF_ROWS][NUM_OF_COLS];
if (!infile)
{
cout << "File (days.txt) does not exist." << endl;
return 1;
}
get_Days(infile, days, NUM_OF_ROWS);
infile.close();
sort_Days(days, NUM_OF_ROWS);
print_Days(days, NUM_OF_ROWS);
return 0;
}
A few things are wrong with the code:
sort_Days
The sort_Days algorithm is throwing errors because you are trying to index days[j - 1] when the nested for loop starts with j = 0. So your initial index is out of bounds.
Furthermore, it seems like you are trying to perform bubble sort on the c-style strings, but your bubble sort implementation is incorrect. Please consult this page for how to implement a simple bubble sort. Hint: the for loop conditional, strcmp and strcpy_s indices need some tweaking.
print_Days
Your print_Days function is incorrect. Here is a version that prints out each c-style string instead of each char within the string:
void print_Days(const char days[][NUM_OF_COLS], const int rows)
{
for (int j = 0; j < rows; j++)
{
cout << days[j] << endl;
}
}
You should know that std::cout understands that when you pass it a c-style string (i.e. the char[NUM_OF_COLS] within days), it means you want to print out the whole string up to the null-terminator.
Your for loop termination conditional was also wrong, because you had j < NUM_OF_COLS, whereas days actually is an array with NUM_OF_ROWS elements, and each element is an array of NUM_OF_COLS size. The way you had it had indexing out of bounds of the days array.
And while I am nitpicking
Try not to use using namespace::std;, there are plenty of reasons why you shouldn't..
The following code works fine when reading two .txt files containing two 5X5 array.
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <stdio.h>
#include <vector>
#include <sstream>
using namespace std;
int main()
{
string myFile, mysecondFile, mystring;
string DIR;
string extension;
int total = 0;
int number_of_lines = 0;
string line;
extension = ".txt";
DIR = "H:\\Year2\\EE273\\EE273\\Week6\\";
cout << "Enter the name of the file: \t";
cin >> myFile;
cout << "Enter the name of the second file: \t";
cin >> mysecondFile;
myFile = DIR + myFile + extension;
mysecondFile = DIR + mysecondFile + extension;
ifstream inFile;
ifstream inFile2;
int i=5;
int j=5;
int i2=5;
int j2=5;
int i3=5;
int j3=5;
int k;
int l;
int Array[5][5];
int Array2[5][5];
int Array3[5][5];
string attempt1,attempt2;
int row = 0;
int col = 0;
int row2 = 0;
int col2 = 0;//i = row
//y = column
inFile.open(myFile.c_str());
if (!inFile) {
cout <<"Error opening file"<<myFile<<endl;
return -1;
}
while (!inFile.eof())
{
getline(inFile, attempt1);
stringstream iss( attempt1 );
string result;
col = 0;
while (getline( iss, result, ','))
{
//cout << result << endl;
Array[row][col] = atoi(result.c_str());
//j = j + 1;
col = col + 1;
}
row = row + 1;
}
inFile.close();
inFile2.open(mysecondFile.c_str());
if (!inFile2) {
cout <<"Error opening file"<<mysecondFile<<endl;
return -1;
}
while (!inFile2.eof())
{
getline(inFile2, attempt2);
stringstream iss( attempt2 );
string result2;
col2 = 0;
while (getline( iss, result2, ','))
{
//cout << result2 << endl;
Array2[row2][col2] = atoi(result2.c_str());
col2 = col2 + 1;
}
row2 = row2 + 1;
}
inFile2.close();
/*for (int i=0;i<5;i++){
for (int j=0; j<5; j++){
cout<<Array[i][j]<<endl;}}
for (int i2=0;i2<5;i2++){
for (int j2=0; j2<5; j2++){
cout<<Array2[i2][j2]<<endl;
}}
Here I am carrying out the multiplication between the two matrices and writing the resulting values to a third matrix.
int Total=0;
i=0;
j2=0;
j=0;
j3=0;
for (i3=0; i3<5; i3++) {
while(j3<5){
while (j<5){
for (i2=0;i2<5;i2++){
Total += Array[i][j]*Array2[i2][j2];
j++;
Array3[i3][j3]=Total;
}}
j=0;
j2++;
j3++;
Total=0;
}
i++;
j=0;
j2=0;
j3=0;
Total=0;
}
My question is: what is the easiest way to modify the code so that it can read two .txt files containing an array of any size and then carry out the multiplication successfully?
EDIT I have to do this using arrays only, I can't use vectors unfortunately.
Am I correct in thinking the new operator is involved?
The "easiest" way would be to do something naive, like reading the file once fully to get the number of rows/cols, then reading the file again to actually store the values in the matrix:
unsigned int rows = 0;
unsigned int cols = 0;
std::string line;
while (std::getline(inFile, line)) {
rows++;
std::stringstream ss(line);
std::string col;
while (std::getline(ss, col, ',')) {
cols++;
}
}
// Now allocate the rows*cols matrix
int** matrix = new int*[rows];
for (int i = 0; i < rows; i++) {
matrix[i] = new int[cols];
}
// and read your values into the matrix ...
// matrix[m][n] = xxx
It's pretty inefficient to read a file twice; and there are other ways to obtain the size beforehand. For example you could have a convention in your input file to include the matrix width/height before the data:
[infile.txt]
3,3
1,2,3
4,5,6
7,8,9
Now you can read the first line of the file, and you'll know that the rest of this file contains a 3x3 matrix. Allocate your matrix with new (similar to above example), then continue to read the rest of the file into it.
Remember to clean up your dynamically allocated matrices with delete[]. There should be 1 call to delete for every call to new.
for (int i = 0; i < rows; i++) {
delete[] matrix[i];
}
delete[] matrix;
Use std::vector instead of raw arrays. E.g. you can push_back an item on a vector. And more crucially, you can create it with a size known only at run-time, e.g. from information in a file.
The easiest approach requires the file to contain the size of the matrix as its first entries. With that, you can fallback to using C (C++ does not tolerate matrices of dynamic size) and do the following:
Read the dimension of the matrix into variables width and heigh.
Allocate the matrix using
int (*dynamicMatrix)[width] = malloc(height*sizeof(*dynamicMatrix));
Reuse your code to fill the matrix.
If you can't fall back to C, and can't use std::vector<>, the only thing left to you is to use a double pointer:
int**dynamicMatrix = new int*[height];
for(size_t i = width; i--; ) dynamicMatrix[i] = new int[width];
Again, this is easiest if you can define the first two numbers in a file to contain the width and height of the matrix in the file. If you can't code these two numbers into your file, you have to grow your dynamic arrays as you go:
size_t lines = 0, allocatedLines = 8;
int** dynamicMatrix = new int*[allocatedLines];
while(/* can read a line */) {
if(lines == allocatedLines) {
int** temp = new int*[allocatedLines *= 2];
for(size_t i = lines; i--; ) temp[i] = dynamicMatrix[i];
delete[] dynamicMatrix;
dynamicMatrix = temp;
}
//add one line
size_t curLineLength = 0, allocatedLineLength = 8;
dynamicMatrix[lines++] = new int[allocatedLineLength];
//fill the line
...
}
A similar block for reallocating a line would need to go into the loop where you read the elements of a single line. This is tedious; but the only way to get better is to use stuff that you are not allowed to use.
Btw: even the reallocating stuff is easier in C, since it provides the realloc() function:
size_t lines = 0, allocatedLines = 8;
int** dynamicMatrix = malloc(allocatedLines * sizeof(*dynamicMatrix));
while(/* can read a line */) {
if(lines == allocatedLines) {
//realloc takes care of copying the data to a new location (if that is necessary):
allocatedLines *= 2;
dynamicMatrix = realloc(dynamicMatrix, allocatedLines * sizeof(*dynamicMatrix));
}
//add one line
size_t curLineLength = 0, allocatedLineLength = 8;
dynamicMatrix[lines++] = malloc(allocatedLineLength * sizeof(**dynamicMatrix));
//fill the line
...
}
Since there is no equivalent to realloc() to work with new/delete, you are required to either use std::vector<> in C++, or to do the copying yourself as above.
Currently I am getting an runtime "assertation error"
Here is the error:
I'm reading words from a text file into dynamically allocated arrays.
this block of code is where I am filling the new arrays.
I know the problem is being caused by this block of code and something about my logic is off just can't see what it is.
//fill new arrays
for( int y = 0; y < new_numwords; y++)
{
for( int i = 0; i < NUM_WORDS; i++)
{
if (!strcmp(SentenceArry[i], EMPTY[0]) == 0)
{
New_SentenceArry[y] = SentenceArry[i];
New_WordCount[y] = WordCount[i];
y++;
}
}
}
Also how would I pass this dynamically allocated 2D array to a function? (the code really needs to be cleaned up as a whole)
char** SentenceArry = new char*[NUM_WORDS]; //declare pointer for the sentence
for( int i = 0; i < NUM_WORDS; i++)
{
SentenceArry[i] = new char[WORD_LENGTH];
}
Here is the full extent of the code.. help would be much appreciated!
Here is what is being read in:
and the current output (the output is how it's suppose to be ):
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
#include <cstring>
#include <cctype>
#include <iomanip>
using std::setw;
using std::left;
using std::cout;
using std::cin;
using std::endl;
using std::ifstream;
int main()
{
const int NUM_WORDS = 17;//constant for the elements of arrays
const int WORD_LENGTH = 50;//constant for the length of the cstrings (NEED TO GIVE THE VALUE ZERO STILL!)
short word_entry = 0; //declare counter
short new_numwords= 0; //declare new word count
char EMPTY[1][4]; //NULL ARRAY
EMPTY[0][0] = '\0';//define it as null
char** SentenceArry = new char*[NUM_WORDS]; //declare pointer for the sentence
for( int i = 0; i < NUM_WORDS; i++)
{
SentenceArry[i] = new char[WORD_LENGTH];
}
int WordCount[NUM_WORDS];//declare integer array for the word counter
for(int i = 0; i < NUM_WORDS; i++)//fill int array
{
WordCount[i] = 1;
}
int New_WordCount[NUM_WORDS] = {0};
ifstream read_text("DataFile.txt"); //read in our text file
if (read_text.is_open()) //check if the the file was opened
{
read_text >> SentenceArry[word_entry];
//REMOVE PUNCTUATION BEFORE BEING READ INTO THE ARRAY
while (!read_text.eof())
{
word_entry++; //increment counter
read_text >> SentenceArry[word_entry]; //read in single words of the text file into the array SentenceArry
char* ptr_ch;//declare our pointer that will find chars
ptr_ch = strstr( SentenceArry[word_entry], ",");//look for "," within the array
if (ptr_ch != NULL)//if true replace it with a null character
{
strncpy( ptr_ch, "\0" , 1);
}//end if
else
{
ptr_ch = strstr( SentenceArry[word_entry], ".");//look for "." within the array
if (ptr_ch != NULL)//if true replace it with a null character
{
strncpy( ptr_ch, "\0" , 1);
}//end if
}//end else
} //end while
}//end if
else
{
cout << "The file could not be opened!" << endl;//display error message if file doesn't open
}//end else
read_text.close(); //close the text file after eof
//WORD COUNT NESTED FOR LOOP
for(int y = 0; y < NUM_WORDS; y++)
{
for(int i = y+1; i < NUM_WORDS; i++)
{
if (strcmp(SentenceArry[y], EMPTY[0]) == 0)//check if the arrays match
{
y++;
}
else
{
if (strcmp(SentenceArry[y], SentenceArry[i]) == 0)//check if the arrays match
{
WordCount[y]++;
strncpy(SentenceArry[i], "\0" , 3);
}//end if
}//end if
}//end for
}//end for
//find how many arrays still contain chars
for(int i = 0; i < NUM_WORDS; i++)
{
if (!strcmp(SentenceArry[i], EMPTY[0]) == 0)
{
new_numwords++;
}
}
//new dynamic array
char** New_SentenceArry = new char*[new_numwords]; //declare pointer for the sentence
for( int i = 0; i < new_numwords; i++)
{
New_SentenceArry[i] = new char[new_numwords];
}
//fill new arrays
for( int y = 0; y < new_numwords; y++)
{
for( int i = 0; i < NUM_WORDS; i++)
{
if (!strcmp(SentenceArry[i], EMPTY[0]) == 0)
{
New_SentenceArry[y] = SentenceArry[i];
New_WordCount[y] = WordCount[i];
y++;
}
}
}
//DISPLAY REPORT
cout << left << setw(15) << "Words" << left << setw(9) << "Frequency" << endl;
for(int i = 0; i < new_numwords; i++) //compare i to the array constant NUM_WORDS
{
cout << left << setw(15) << New_SentenceArry[i] << left << setw(9) << New_WordCount[i] << endl; //display the contents of the array SentenceArry
}
//DEALLOCATION
for( int i = 0; i < NUM_WORDS; i++)//deallocate the words inside the arrays
{
delete [] SentenceArry[i];
}
for(int i = 0; i < new_numwords; i++)
{
delete [] New_SentenceArry[i];
}
delete [] SentenceArry; //deallocate the memory allocation made for the array SentenceArry
delete [] New_SentenceArry;//deallocate the memory allocation made for the array New_SentenceArry
}//end main
There are several issues with the code, not withstanding that this could be written using C++, not C with a sprinkling of C++ I/O..
Issue 1:
Since you're using c-style strings, any copying of string data will require function calls such as strcpy(), strncpy(), etc. You failed in following this advice in this code:
for( int y = 0; y < new_numwords; y++)
{
for( int i = 0; i < NUM_WORDS; i++)
{
if (!strcmp(SentenceArry[i], EMPTY[0]) == 0)
{
New_SentenceArry[y] = SentenceArry[i]; // This is wrong
New_WordCount[y] = WordCount[i];
y++;
}
}
}
You should be using strcpy(), not = to copy strings.
strcpy(New_SentenceArry[y], SentenceArry[i]);
Issue 2:
You should allocate WORD_LENGTH for both the original and new arrays. The length of the strings is independent of the number of strings.
char** New_SentenceArry = new char*[new_numwords]; //declare pointer for the sentence
for( int i = 0; i < new_numwords; i++)
{
New_SentenceArry[i] = new char[new_numwords];
}
This should be:
char** New_SentenceArry = new char*[new_numwords]; //declare pointer for the sentence
for( int i = 0; i < new_numwords; i++)
{
New_SentenceArry[i] = new char[WORD_LENGTH];
}
Issue 3:
Your loops do not check to see if the index is going out of bounds of your arrays.
It seems that you coded your program in accordance to the data that you're currently using, instead of writing code regardless of what the data will be. If you have limited yourself to 17 words, where is the check to see if the index goes above 16? Nowhere.
For example:
while (!read_text.eof() )
Should be:
while (!read_text.eof() && word_entry < NUM_WORDS)
Issue 4:
You don't process the first string found correctly:
read_text >> SentenceArry[word_entry]; // Here you read in the first word
while (!read_text.eof() )
{
word_entry++; //increment counter
read_text >> SentenceArry[word_entry]; // What about the first word you read in?
Summary:
Even with these changes, I can't guarantee that the program won't crash. Even it it doesn't crash with these changes, I can't guarantee it will work 100% of the time -- a guarantee would require further analysis.
The proper C++ solution, given what this assignment was about, is to use a std::map<std::string, int> to keep the word frequency. The map would automatically store similar words in one entry (given that you remove the junk from the word), and would bump up the count to 1 automatically, when the entry is inserted into the map.
Something like this:
#include <string>
#include <map>
#include <algorithm>
typedef std::map<std::string, int> StringMap;
using namespace std;
bool isCharacterGarbage(char ch)
{ return ch == ',' || ch == '.'; }
int main()
{
StringMap sentenceMap;
//...
std::string temp;
read_text >> temp;
temp.erase(std::remove_if(temp.begin(), temp.end(), isCharacterGarbage),temp.end());
sentenceMap[temp]++;
//...
}
That code alone does everything your original code did -- keep track of the strings, bumps up the word count, removes the junk characters from the word before being processed, etc. But best of all, no manual memory management. No calls to new[], delete[], nothing. The code just "works". That is effectively 5 lines of code that you would just need to write a "read" loop around.
I won't go through every detail, you can do that for yourself since the code is small, and there are vast amounts of resources available explaining std::map, remove_if(), etc.
Then printing out is merely going through the map and printing each entry (string and count). If you add the printing, that may be 4 lines of extra code. So in all, practically all of the assignment is done with effectively 10 or so lines of code.
Remove below code.
for(int i = 0; i < new_numwords; i++)
{
delete [] New_SentenceArry[i];
}
I am writing code to read in a set of numbers and then display them in a 4x4 grid on screen, the program will then determine if it is a magic square. My question is how can I get the user to input the numbers into a file that is shown in the readData method so that when that method is called it will display the users grid.
Also where does the file data.txt get stored?
thanks
#include<iostream>
#include<fstream>
using namespace std;
const int dimension = 4; // dimension for the array
typedef int Sq[dimension] [dimension]; // declare vector for type names
void ReadData(Sq square ) // read data from file
{ ifstream inFile;
char fileName[13] = "data.txt";
inFile.open (fileName); // open file for reading
for (int r = 0; r < dimension; r++) // row loop
for ( int c = 0; c < dimension; c++) // column loop
inFile >> square[r][c]; // read data into matrix
inFile.close( ); // close the file
}
void Display ( const Sq square ) // display matrix
{ cout << " Magic Square Program " << endl << endl;
for (int r = 0; r < dimension; r++)
{ for ( int c = 0; c < dimension; c++)
{ cout.width(6); //set output width to 6 characters
cout << square[r][c] << "\t "; // display numbers
}
cout << endl;
}
}
bool magicSquare( Sq square) // add rows, columns, and diagonals
{ int firstSum = 0, sum;
bool magic = true;
for (int r = 0; r < dimension; r++) // add 1st column for a comparison
firstSum += square[r][1];
for (int r = 1; r < dimension; r++) // row loop first when adding rows
{ sum = 0;
for ( int c = 0; c < dimension; c++)
sum += square[r][c]; // add row
if ( sum != firstSum) // check for magic failure
return (false); // not magic
}
for ( int c = 0; c < dimension; c++) // column loop first when adding columns
{ sum = 0;
for (int r = 0; r < dimension; r++)
sum += square[r][c]; // add columns
if ( sum != firstSum) // check for magic failure
return (false); // not magic
}
sum = 0;
for (int r = 0; r < dimension; r++)
sum += square[r][r]; // add front diagonal
if ( sum != firstSum) // check for magic failure
return (false); // not magic
sum = 0;
for (int r = 0; r < dimension; r++)
sum += square[r][dimension - r - 1]; // add back diagonal
if ( sum != firstSum) // check for magic failure
return (false); // not magic
else
return (true);
} // end magicSquare function
int main( )
{
Sq square;
ReadData( square); // read data from file
Display ( square); // display matrix
if ( magicSquare(square) ) // check for magic property
cout << "\n This Square is Magic \n " << endl;
else
cout << "\n This Square is Not Magic \n " << endl;
system("Pause");
return(0);
}
The easiest way is to make the program take the filename as a command-line argument. Main should really look like this, where argc is the number of arguments, and argv[] is and array of char pointers to them (argv[0] is always the name of the executable). See What does int argc, char *argv[] mean?
int main(int argc, char * argv[])
So then, you do
if (argc == 2)
{
ReadData(square, argv[1]);
...
}
else
...
And ReadData would look like this:-
void ReadData(Sq &square, const std::string &filename) // read data from file
{
ifstream inFile;
inFile.open (filename); // open file for reading
NOTE! you need to take square as a reference parameter (&square) otherwise your input data just gets ignored.
My question is how can I get the user to input the numbers into a file that is shown in the readData method?
Ask politely? Since it's a file on the disk, user has to fill it before the program starts. You could use appropriate ifstream flag to not create the file if it doesn't exist, and display an error message instead, terminating the program afterwards.
Also where does the file data.txt get stored?
In the current execution path of the binary. This may or may not be the folder where the binary is located.
As a side note, as you are using C++, std::array<> might be a better fit than C-style arrays.