C++ C++;读取带空格的字符串

C++ C++;读取带空格的字符串,c++,istream,C++,Istream,我有这样的文件: 59 137 New York 137 362 Syracuse 216 131 New Jersey ... .. . f.open("map.txt"); string city; int x , y; f >> x >> y; getline(f,city); while (!f.fail()) { f >> x >> y; getline(f,city); } f.close()

我有这样的文件:

59 137 New York
137 362 Syracuse
216 131 New Jersey
...
..
.
  f.open("map.txt");
  string city;
  int x , y;
  f >> x >> y;
  getline(f,city);

  while (!f.fail()) {
  f >> x >> y;
  getline(f,city);
  }
  f.close();
我想把它读给一个结构: X-Y-城市名称

  char city[100];
  int x , y;
  f.open("map.txt");
  f >> x >> y >> city;
  while (!f.fail()) {
    f >> x >> y >> city;
  }
  f.close();
问题是,这个城市在下一个空间之前只能阅读,所以从纽约开始只能阅读新的内容。
我应该如何以简单而聪明的方式阅读一行的其余部分?

您可以这样做:

59 137 New York
137 362 Syracuse
216 131 New Jersey
...
..
.
  f.open("map.txt");
  string city;
  int x , y;
  f >> x >> y;
  getline(f,city);

  while (!f.fail()) {
  f >> x >> y;
  getline(f,city);
  }
  f.close();

文件的格式似乎暗示城市名称以行尾结束,而不是空格

你可以使用


使用getline(f,city)表示城市。所以,你有f>>x>>y;getline(f,城市)

此代码正确读取空格并处理文件结尾。我认为其他答案都不能做到这一点

while ((f >> x >> y).getline(city, 100))
{
}
有关如何正确测试文件结尾的更多信息,请参阅


当然,你应该像其他人所说的那样,使用
std::string以简单的方式做事。

谢谢你的回复,while内部不应该也有同样的变化吗?@Simon是的!谢谢你接电话。注意,我还简化了代码。
istream
可以单独用于“谢谢”,我是否还需要将char city[100]更改为string city@Simon虽然您不需要这样做,但是
std::string
提供了许多数组无法提供的保护。在这种情况下,您需要
std::getline(f,city)您应该将城市设置为
std::string