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 が設定されているため操作が失敗します。eofbit が設定された後にストリーム状態をリセットするため、コードのss.clear();後に​​追加すると動作します。ss >> temp;

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 に答える