I am trying to write a console application that reads from file in the form (all are integers)
Example:
c
k
a1 a2 a3
a4 a5 a6
a7 a8 a9
where first line is for number of rows and second for number of columns and c, k and an, all are integers.
if I cout<<row
or column it puts the program into loop.
I’ve tried reading the whole line with
getline(my file, line)
and then
row=stoi(line);
but to no avail.
EXAMPLE CODE
void read_row_and_column_function(int* fucntion_selector,string* ptr_to_name_of_file)
{
int row, column;
ifstream myfile;
myfile.open(*ptr_to_name_of_file);
if(myfile.is_open())
{
myfile>>row;
myfile>>column;
myfile.close();
}
cout<<row;
}
Expected result is row.
EDIT FOR FULL CODE
#include<iostream>
#include<fstream>
using namespace std;
void file_name_getter();
void read_ploynomials_and_variables_function(int* fucntion_selector,string* ptr_to_name_of_file)
{
int polynomials, variables;
ifstream myfile;
myfile.open(*ptr_to_name_of_file);
if(myfile.is_open())
{
myfile>>polynomials;
myfile>>variables;
myfile.close();
}
cout<<polynomials<<endl;
}
void data_structure_seletor(string* ptr_to_name_of_file)
{
cout<<"Select the desired data structure to store polynomials\n1. Matrix\n2. Linked List\n3. Change file name\n0. EXIT\nINPUT: ";
int data_structure_choice;
cin>>data_structure_choice;
while(1)
{
if (data_structure_choice==1)
{
read_ploynomials_and_variables_function(&data_structure_choice, ptr_to_name_of_file);
}
else if (data_structure_choice==2)
{
read_ploynomials_and_variables_function(&data_structure_choice, ptr_to_name_of_file);
}
else if (data_structure_choice==3)
{
cout<<"\n";
file_name_getter();
}
else if (data_structure_choice==0)
{
return;
}
else
{
cout<<"\nIncorrect option. TRY AGAIN!!\n\n";
}
}
}
void file_name_getter()
{
string name_of_file, extension=".txt";
cout<<"Enter name of the file you want to open\nNOTE: \".txt\" extension will be appended by the program\nNAME of file: ";
cin>>name_of_file;
name_of_file=name_of_file+extension;
data_structure_seletor(&name_of_file);
}
int main()
{
file_name_getter();
return 0;
}
The files are in the same folder. Example file name 10x5, 3x3 etc
EDIT
__The query is solved now. Problem was in void data_structure_selector()
in while(1)
loop.
You read data_structure_choice
only once outside the loop. And don't modify it's value inside the loop. Did you mean, to read the input inside the loop?
You could use the part also as the loop-condition to loop until eof is reached or a value was entered, that can't be parsed as int:
int data_structure_choice;
while(cin>>data_structure_choice) {
...
}
Also keep in mind, that functions like getline(myFile, line)
or myfile >> row
will not terminate your program if the file is completly read or something.