C ++读取带空格的字符串
问题描述:
我有这样的文件:
59 137 New York
137 362 Syracuse
216 131 New Jersey
...
..
.
,我想将其读取为一个结构:X-Y-城市名称
and I would like to read it to a structure: X - Y - name of a city
char city[100];
int x , y;
f.open("map.txt");
f >> x >> y >> city;
while (!f.fail()) {
f >> x >> y >> city;
}
f.close();
问题是,该城市只读取下一个空格,因此从纽约开始,它只读取New.我应该如何以一种简单而又聪明的方式阅读一行的其余部分?
Problem is, that city reads only until next space, so from New York it reads only New. How should I read whole rest of a line, in some easy and smart way ?
答
文件格式似乎暗示城市的名称以行的结尾结尾,而不是>空格.
The format of your file seems to imply that the name of the city ends at the end of a line, not a space.
您可以使用 getline
阅读该表格a>
You can read that form using getline
char city[100];
int x , y;
f.open("map.txt");
while ( f ) {
f >> x >> y;
f.getline(city, 100);
}
f.close();