在控制台上输出我从文件中读取的整数,使程序陷入无限循环?

Outputting the integer on console that I have read from the file, sticks program into infinite loop?

我正在尝试编写一个控制台应用程序,该应用程序以以下形式从文件中读取(均为整数)

示例:

c

k

a1  a2  a3

a4  a5  a6

a7  a8  a9

其中第一行是行数,第二行是列数,ckan,都是整数。

如果我 cout<<row 或专栏,它会使程序进入循环。

我试过用

读整行

getline(my file, line)

然后

row=stoi(line);

但没有可用

示例代码

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;
}

预期结果为行。

编辑完整代码

#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;
}

文件在同一个文件夹中。示例文件名 10x53x3

编辑

__The 查询现已解决。问题出在 while(1) 循环中的 void data_structure_selector()

您在循环外data_structure_choice 只读了一次。并且不要在循环内修改它的值。您的意思是读取循环中 的输入吗?

您也可以将该部分用作循环条件来循环直到达到 eof 或输入一个值,该值不能被解析为 int:

    int data_structure_choice;

    while(cin>>data_structure_choice) {
        ...
    }

另外请记住,如果文件被完全读取或发生其他情况,getline(myFile, line)myfile >> row 等函数将 不会 终止您的程序。