为什么这段代码重复地只从字符串流中提取第一个字符串

Why is this code repeatedly extracting only the first string from the stringstream?

本文关键字:字符串 第一个 提取 段代码 代码 为什么      更新时间:2023-10-16

我正在一个实验室工作,该实验室需要解析文件中的字符串,以便用碎片填充游戏板。输入文件的格式如下:

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

是什么导致只重复提取字符串流中的第一个字符串?如何提取连续的字符串,直到行的末尾?

在每行中重新创建stringstream实例:

std::stringstream(tempString) >> var1;   // creates new stringstream instance
std::stringstream(tempString) >> var2;   // creates new stringstream instance
std::stringstream(tempString) >> var3;   // creates new stringstream instance

您应该使用局部变量来保留流的状态。我还用istringstream替换了stringstream,因为您只是在阅读流。

std::istringstream ss(tempString);       // creates new stringstream instance just here
ss >> var1;                              // reads from the same stringstream
ss >> var2;                              // reads from the same stringstream
ss >> var3;                              // reads from the same stringstream