Stringstream 无法正确转换
Stringstream won't convert properly
首先,我使用的是 Windows 8.1、Visual Studio 2013 Express 和 c++。虽然不知道我使用的是哪个 C++ 标准。
我完全不熟悉编程,所以我可能错过了这个函数中的一些基本部分。我正在做一个有 10 个问题的测验,这个测验是关于 MJ 去世的时间。我正在尝试确保如果用户使用 getline()
.
输入 int
以外的内容,程序不会崩溃
我了解了 stringstream
并进行了转换。它应该将 "playerAnswer" 转换为 int
。
我正在使用 #include <iostream>
#include <string>
#include <sstream>
和 using namespace std;
int question_3()
{
cout << "Question 3:\n";
string playerAnswer = "";
int convertedAnswer = 0;
cout << "Which year did Michael Jackson die? 2008, 2009 or 2010?\n" \
"Your answer: ";
while (true)
{
getline(cin, playerAnswer);
stringstream convHolder; // EDIT: Got an answer and it now works.
// Forgot (playerAnswer) in convHolder
if (convHolder >> convertedAnswer)
{
if (convertedAnswer == 2009)
{
cout << endl << "Correct! \nOn August 29 1958 the legend was born. \n" \
"On June 25 2009 he passed away in his rented mansion in Holmby Hills.\n";
cout << endl;
return 1;
}
else
{
cout << endl << "Wrong. \nOn August 29 1958 the legend was born. \n" \
"On June 25 2009 he passed away in his rented mansion in Holmby Hills.\n";
cout << endl;
return 0;
}
}
else
{
cout << "Invalid number, please try again: ";
}
}
}
如果您能让它按预期工作并使用更好的 way/with 更短的代码,我将非常有兴趣学习它 :) 欢迎大家提供任何意见!
/尼克
您没有初始化字符串流以使用用户输入的字符串:
stringstream convHolder;
应该是
stringstream convHolder(playerAnswer);
首先,我使用的是 Windows 8.1、Visual Studio 2013 Express 和 c++。虽然不知道我使用的是哪个 C++ 标准。
我完全不熟悉编程,所以我可能错过了这个函数中的一些基本部分。我正在做一个有 10 个问题的测验,这个测验是关于 MJ 去世的时间。我正在尝试确保如果用户使用 getline()
.
int
以外的内容,程序不会崩溃
我了解了 stringstream
并进行了转换。它应该将 "playerAnswer" 转换为 int
。
我正在使用 #include <iostream>
#include <string>
#include <sstream>
和 using namespace std;
int question_3()
{
cout << "Question 3:\n";
string playerAnswer = "";
int convertedAnswer = 0;
cout << "Which year did Michael Jackson die? 2008, 2009 or 2010?\n" \
"Your answer: ";
while (true)
{
getline(cin, playerAnswer);
stringstream convHolder; // EDIT: Got an answer and it now works.
// Forgot (playerAnswer) in convHolder
if (convHolder >> convertedAnswer)
{
if (convertedAnswer == 2009)
{
cout << endl << "Correct! \nOn August 29 1958 the legend was born. \n" \
"On June 25 2009 he passed away in his rented mansion in Holmby Hills.\n";
cout << endl;
return 1;
}
else
{
cout << endl << "Wrong. \nOn August 29 1958 the legend was born. \n" \
"On June 25 2009 he passed away in his rented mansion in Holmby Hills.\n";
cout << endl;
return 0;
}
}
else
{
cout << "Invalid number, please try again: ";
}
}
}
如果您能让它按预期工作并使用更好的 way/with 更短的代码,我将非常有兴趣学习它 :) 欢迎大家提供任何意见!
/尼克
您没有初始化字符串流以使用用户输入的字符串:
stringstream convHolder;
应该是
stringstream convHolder(playerAnswer);