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

问题描述 投票:0回答:1

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

示例:

c

k

a1  a2  a3

a4  a5  a6

a7  a8  a9

其中第一行是行数,第二行是列数和k]和an,它们都是整数。如果我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; }

文件位于同一文件夹中。示例文件名
10x5,

3x3

编辑

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

我正在尝试编写一个从文件中读取文件的控制台应用程序(所有都是整数),例如:ck a1 a2 a3 a4 a5 a5 a6 a7 a8 a9其中第一行是行数,第二行是……] >

您在循环外读取了data_structure_choice
仅一次。并且不要在循环内修改它的值。您是说要读取输入

inside

循环吗?
您也可以将零件用作循环条件,直到达到eof或输入了不能解析为int的值为止的循环条件: int data_structure_choice; while(cin>>data_structure_choice) { ... }

还请记住,如果文件已被完全读取或类似操作,则getline(myFile, line)myfile >> row之类的功能将

不是终止程序。
c++ file fstream file-handling ifstream
1个回答
0
投票
仅一次。并且不要在循环内修改它的值。您是说要读取输入

inside

循环吗?
© www.soinside.com 2019 - 2024. All rights reserved.