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

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

本文关键字:整数 程序 无限循环 插入 读取 控制台 输出 文件      更新时间:2023-10-16

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

示例:

c
k
a1  a2  a3
a4  a5  a6
a7  a8  a9

其中,第一行表示行数,第二行表示列数,ckan均为整数。

如果Icout<<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 polynomialsn1. Matrixn2. Linked Listn3. Change file namen0. EXITnINPUT: ";
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!!nn";
}
}
}
void file_name_getter()
{
string name_of_file, extension=".txt";
cout<<"Enter name of the file you want to opennNOTE: ".txt" extension will be appended by the programnNAME 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

编辑

__查询现在已解决。问题出现在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这样的函数将不会终止程序。

相关文章: