0

我不确定我的代码有什么问题。我希望在 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;
4

1 回答 1

1

执行插入和提取时,应始终检查是否成功:

例子

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;
于 2012-06-15T03:26:58.810 回答