重新使用stringstream对象的问题 [英] Problem with re-using a stringstream object

查看:120
本文介绍了重新使用stringstream对象的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 <$ c> 

我试图在C ++中使用数字处理输入时使用安全做法, $ c> #include< iostream>
#include< string>
#include< sstream>
using namespace std;

int main()
{
int first,second;
string input;

stringstream sstream;

cout<< First integer:;
getline(cin,input);
sstream.str(input);
sstream>>第一;

cout<<第一< endl //显示用户输入的整数

cout<< 第二个整数:;
getline(cin,input);
sstream.str(input);
sstream>>第二;

cout<<第二< endl //以整数显示用户输入

getline(cin,input); // pause program

return 0;
}

然而,第二次它似乎给变量'second'任意值。这是输出:

 第一个整数:1 
1
第二个整数:2
2293592

如果我声明两个stringstream对象并分别用于这两个变量,它似乎工作正常。这是否意味着我不能重新使用stringstream对象的方式,我想尝试?在我真正的程序中,我打算处理从用户多于两个输入值,所以我只想确保是否有另一种方式,而不是制作多个stringstream对象。我怀疑这是非常相关的,但我在Windows XP和我使用MinGW作为我的编译器。



我非常感谢任何帮助。

解决方案

使用 sstream.clear(); sstream> ;第一;


I'm trying to use safe practices in handling input with numbers only in C++, so I use a stringstream object as so:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
    int first, second;
    string input;

    stringstream sstream;

    cout << "First integer: ";
    getline(cin, input);
    sstream.str(input);
    sstream >> first;

    cout << first << endl; //display user input in integers

    cout << "Second integer: ";
    getline(cin, input);
    sstream.str(input);
    sstream >> second;

    cout << second << endl; //display user input in integers

    getline(cin, input); //pause program

    return 0;
}

However, the second time around it seems to give the variable 'second' an arbitrary value. This is the output:

First integer: 1
1
Second integer: 2
2293592

If I declare two stringstream objects and use them respectively for both variables it seems to work fine. Does this mean that I cannot re-use a stringstream object in the way I'm trying to do? In my real program I intend to handle much more than two input values from the user, so I just want to make sure if there's another way instead of making multiple stringstream objects. I doubt it's of great relevance but I'm on Windows XP and I'm using MinGW as my compiler.

I greatly appreciate any help.

解决方案

Use sstream.clear(); after sstream >> first;.

这篇关于重新使用stringstream对象的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆