我不确定我的代码有什么问题。我希望在 for 循环的每次迭代中更新字符并将其插入到字符串流中,并提取到一个字符串,稍后我可以使用该字符串附加到 char[] 变量。我希望收到的变量内容的输出是: CPU代表什么? A. 中央处理器 B. 控制编程单元 C. 中央编程单元 D.控制处理单元 相反,我得到了全A。如何更新流中的值,以便 temp 采用值“A.”、“B.”、“C.”和“D.”。我对 C++ 并不陌生,但对使用 stringstream 很陌生。谁能解释一下发生了什么以及我如何解决它?我在 Unix 环境中使用 g++ 编译器。
char content[1096];
int numOfChoices;
char letterChoice = 'A';
string choice, temp;
stringstream ss;
strcpy ( content, "What does CPU stand for?");
cout << "How many multiple choice options are there? ";
cin >> numOfChoices;
cin.ignore(8, '\n');
for (int i = numOfChoices; i > 0; i--)
{
strcat (content, "\n");
ss << letterChoice << ".";
ss >> temp;
strcat(content, temp.c_str());
ss.str("");
cout << "Enter answer for multiple choice option "
<< letterChoice++ <<":\n--> ";
getline (cin, choice);
strcat(content, " ");
strcat(content, choice.c_str());
}
cout << content << endl;
最佳答案
当你执行插入和提取时,你应该始终检查它是否成功:
示例
if (!(ss << letterChoice << "."))
{
cout << "Insertion failed!" << endl;
}
这样,您就可以立即知道出现了问题。
在第一个循环中,当您执行 ss >> temp;
时它提取流中的所有字符并将它们放入 temp
中。然而,到达文件末尾,因此 eofbit 被设置。因此,在下一个循环中,当您执行 ss << letterChoice << ".";
时,操作失败,因为 eofbit 已设置。如果添加 ss.clear();
之后ss >> temp;
该代码将起作用,因为您在设置 eofbit 后重置了流状态。
但是,您不需要 stringstream
或代码中所有旧的 C 函数。你可以用 std::string
做任何事像这样:
string content = "";
int numOfChoices;
char letterChoice = 'A';
string choice;
content += "What does CPU stand for?";
cout << "How many multiple choice options are there? ";
cin >> numOfChoices;
cin.ignore(8, '\n');
for (int i = numOfChoices; i > 0; i--)
{
content += "\n";
content += letterChoice;
content += ".";
cout << "Enter answer for multiple choice option "
<< letterChoice++ <<":\n--> ";
getline (cin, choice);
content += " ";
content += choice;
}
cout << content << endl;
关于c++ - 如何在 C++ 循环中将新字符插入 StringStream 并提取到字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11043149/