为什么这段代码只重复提取stringstream中的第一个字符串?

时间:2014-09-27 17:21:27

标签: c++ stream stringstream extraction

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

black checker X 1 1
black checker X 2 0
red checker O 0 6
red checker O 1 5

下面是我的代码,它从stringstream-wrapped 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中的第一个字符串?如何提取连续字符串直到行尾?

1 个答案:

答案 0 :(得分:2)

您在每行重新创建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

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

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