【发布时间】:2014-11-22 12:10:40
【问题描述】:
我正在一个实验室工作,该实验室需要从文件中解析字符串,以便用棋子填充游戏板。输入文件的格式如下:
black checker X 1 1
black checker X 2 0
red checker O 0 6
red checker O 1 5
下面是我从字符串流包装的 tempString 中提取字符串的代码:
int readGamePieces(std::ifstream & fileStream, std::vector<game_piece> & pieces, int widthBoard, int heightBoard) {
// attributes of the game piece being read from file
std::string color;
std::string name;
std::string display;
int xCoord = 0;
int yCoord = 0;
std::string tempString;
while (getline(fileStream, tempString)) {
std::cout << "getting new line" << std::endl;
std::cout << "contents of line: " << tempString << std::endl;
std::stringstream(tempString) >> color;
std::stringstream(tempString) >> name;
std::stringstream(tempString) >> display;
std::stringstream(tempString) >> xCoord;
std::stringstream(tempString) >> yCoord;
std::cout << "Game Piece Color: " << color << std::endl;
std::cout << "Game Piece Name: " << name << std::endl;
std::cout << "Game Piece Display: " << display << std::endl;
std::cout << "Game Piece xCoord: " << xCoord << std::endl;
std::cout << "Game Piece yCoord: " << yCoord << std::endl;
}
当我通过命令行运行这个程序时,我得到如下输出:
getting new line
contents of line: black checker X 1 1
Game Piece Color: black
Game Piece Name: black
Game Piece Display: black
Game Piece xCoord: 0
Game Piece yCoord: 0
getting new line
contents of line: black checker X 2 0
Game Piece Color: black
Game Piece Name: black
Game Piece Display: black
Game Piece xCoord: 0
Game Piece yCoord: 0
getting new line
contents of line: red checker X 0 6
Game Piece Color: red
Game Piece Name: red
Game Piece Display: red
Game Piece xCoord: 0
Game Piece yCoord: 0
getting new line
contents of line: red checker X 1 5
Game Piece Color: red
Game Piece Name: red
Game Piece Display: red
Game Piece xCoord: 0
Game Piece yCoord: 0
是什么导致重复提取字符串流中的第一个字符串?以及如何提取连续的字符串直到行尾?
【问题讨论】:
-
因为每次尝试提取值时都会创建一个新的字符串流。创建一个字符串流,然后从中提取。
标签: c++ stream stringstream extraction