文字列ストリームの使用

プログラミングQA


Q. 質問は、1,2,3 のような入力を取り、1(\n)2(\n)3 を出力することです..
そのためにstringstreamを使用していますが、最後の整数については、最後と最初の整数を一緒に取る整数の問題を引き起こしています
-> 区切り文字 (,) を使用した getline や、「,」を「\n」に置き換える関数の作成など、他の方法も認識しています。
-> この stringstream プログラムの間違いを見つけたい..

私が試したこと:

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    char waste;
    int a,b,c;
    string input;
    cin >> input;
    stringstream ss;
    ss << input;
    ss >> a;
    ss << input;
    ss >> waste;
    ss << input;
    ss >> b;
    ss << input;
    ss >> waste;
    ss << input;
    ss >> c;
    cout << a << endl << b << endl << c << endl;   
    return 0;
}

入力

1,2,3
出力

1
2
31 (入力文字列の最初の文字と最後の文字を取りました)
期待される出力

1
2
3
変化する

入力が 1,2,3 ではなく 1,2,3/ の場合、正しく動作しています

これ

C++
#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    // Enter your code here. Read input from STDIN. Print output to STDOUT 
    char waste;
    int a,b,c;
    string input;
    cin >> input;
    stringstream ss(input);
    ss >> a >> waste >> b >> waste >> c;
    cout << a << "\n" << b << "\n" << c << "\n";
    return 0;
}

私のために働きます。

完全な文字列テキストを読んでいます ("1,2,3") の中へ ss 毎回、1文字だけではありません。 コードを次のように変更して、私の意味を確認してください。

C++
char waste;
int a,b,c;
string input;
cin >> input;
stringstream ss;
ss << input;
cout << "ss: " << ss.str() << endl;
ss >> a;
ss << input;
ss >> waste;
cout << "ss: " << ss.str() << endl;
ss << input;
ss >> b;
ss << input;
ss >> waste;
cout << "ss: " << ss.str() << endl;
ss << input;
ss >> c;
cout << a << endl << b << endl << c << endl;



Source link

コメント

タイトルとURLをコピーしました