从C ++中的文件读取 [英] Read from a file in C++
问题描述
4;
Spadina; 76 156
Bathurst; 121 291
Keele; 70 61
Bay; 158 158 < br>
4;
Spadina;76 156
Bathurst;121 291
Keele;70 61
Bay;158 158
这是文件包含的内容。我需要读取它们并将它们保存为变量。
This is what file contains in it. I need to read them and save them into variables.
4用于动态内存分配。 4表示有4个站。
Spadina,Bathrust等。他们是车站名。第一个数字,紧接车站名称后,是学生通行证的数量,第二个数字是成人通行证的数量。
4 is for dynamic memory allocation. 4 means there are 4 stations. Spadina, Bathrust, etc.. they are station names. first number, which comes right after station names, is number of student passes and the second number is number of adult pass.
因此,基本上我有4个变量,它们是:
So, basically I have 4 variables and they are;
int numberOfStation;
int studentPass;
int adultPass;
string stationName;
我花了4小时,但仍然无法读取文件并将其保存到变量
。谢谢。
I spent 4 hours but still cannot read the file and save it into variable
Thank you.
推荐答案
首先将您的变数分组。
struct MyStruct
{
int studentPass;
int adultPass;
string stationName;
};
现在读取文件中struct的大小并动态分配。
Now read size of struct in file and allocate it dynamically
MyStruct *p;
s >> N;
p = new MyStruct[N];
现在在for循环中,您读取的字符串使用分隔符';'
和其他两个vars是int
Now in for loop you read string with delimiter ';'
and other two vars are ints
for (int i = 0; i < N; i++)
{
getline(s, p[i].stationName, ';');
s >> p[i].studentPass >> p[i].adultPass;
}
其中var s
是istream类型的变量,标志 std :: in
Where var s
is istream type of variable with flag std::in
这篇关于从C ++中的文件读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!