通过输入流获取输入并将其存储在结构变量中

时间:2015-10-16 22:18:54

标签: c++

我通过inputstream接收用户输入并将其存储在数组中,下面的代码描述了我的场景:

istringstream iss(line);
 // The below code is incorrect 
  while (iss >> i)
{

    image[j].r = i;
    image[j].g = i;// this should be the next character 
    image[j].b = i;// this should be the character after the previous one 
    j++
}

问题:我想一次读取字符3并将它们存储在我的数组结构中。我怎样才能做到这一点?

注意:图像是某种结构的数组

1 个答案:

答案 0 :(得分:1)

您应该直接阅读所需的值:

size_t j = 0;
istringstream iss(line);

while (iss >> image[j].r >> image[j].g >> image[j].b) {
   j++;
}

您需要确保image足够大以容纳所有读取的值。

可能更灵活的解决方案是使用std::vector而不是原始数组:

istringstream iss(line);
std::vector<MyStruct> image;

MyStruct item;
while (iss >> item.r >> item.g >> item.b) {
   image.push_back(item);
}
相关问题