在控制台上输出我从文件中读取的整数,将程序插入无限循环
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
其中,第一行表示行数,第二行表示列数,c、k和an均为整数。
如果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;
}
这些文件在同一个文件夹中。示例文件名10x5、3x3等
编辑
__查询现在已解决。问题出现在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
这样的函数将不会终止程序。
相关文章:
- 内联程序集printf将整数解释为地址
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 我正在尝试制作一个程序,在添加 n 天(整数)后告诉一个人什么是一天(例如星期一等)
- 编写一个读取五个整数并执行一些任务的C++程序
- 为什么这个程序接受整数和字母数字输入并打印它们? C++ 中的 std::string 也采用整数值吗?
- 16 位系统中的程序如何访问大于 65535 的整数,但不能访问地址
- 我需要编写一个程序来读取一个文件,该文件将输出所有唯一的整数,如果已经看到整数,它将被关闭
- 编写一个程序,提示用户输入一个整数,然后输出数字的单个数字和数字的总和
- 在控制台上输出我从文件中读取的整数,将程序插入无限循环
- 向文件读取和写入整数的程序
- MongoDB C++ 驱动程序 - 8 位和 16 位整数?
- 编写一个程序,输入整数 n 并打印该数字的字符数(符号除外)
- 我的程序不断四舍五入到最接近的整数
- 为什么在此C++程序上添加负整数会导致正整数?
- 调用 Parse int 函数时编译 parse 整数程序时出现问题
- C++程序,将整数输入转换为字符的问题
- 我的C++程序有问题.涉及动态调整整数数组的大小
- 程序终止,而不是继续整数输入验证循环
- 查找混合整数程序的绑定约束