[英]How cast char to int in C++? (File Handling)
Lets say I have a txt file list.txt
可以说我有一个txt文件list.txt
The txt file has list of integers , txt文件包含整数列表,
88
894
79
35
Now I am able to open the file and display the contents in it but not able to store it in an integer array. 现在,我可以打开文件并显示其中的内容,但不能将其存储在整数数组中。
int main()
{
ifstream fin;
fin.open("list.txt");
char ch;
int a[4],i=0;
while((!fin.eof())&&(i<4))
{
fin.get(ch);
a[i]=(int)ch;
cout<<a[i]<<"\n";
i++;
}
fin.close();
return 0;
}
Please help!! 请帮忙!!
You can use >>
to read text-formatted values: 您可以使用>>
来读取文本格式的值:
fin >> a[i]
You should check for the end of the file after trying to read, since that flag isn't set until a read fails. 你应该尝试读取后检查该文件的结尾,因为这标志没有设置,直到读取失败。 For example: 例如:
while (i < 4 && fin >> a[i]) {
++i;
}
Note that the bound needs to be the size of the array; 注意边界必须是数组的大小。 yours is one larger, so you might overrun the array if there are too many values in the file. 您的值要大一个,因此如果文件中的值太多,则可能会超出数组。
Try the following 尝试以下
#include <iostream>
#include <fstream>
int main()
{
const size_t N = 4;
int a[N];
std::ifstream fin( "list.txt" );
size_t i = 0;
while ( i < N && fin >> a[i] ) i++;
while ( i != 0 ) std::cout << a[--i] << std::endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.