【发布时间】:2022-01-17 14:50:29
【问题描述】:
我有以下代码,其中有两个函数在满足条件时应该抛出异常。不幸的是,第二个带字符串的似乎不起作用,我不知道出了什么问题
#include "iostream"
#include "stdafx.h"
#include "string"
using namespace std;
struct P
{
int first;
string second;
};
void T(P b)
{ if (b.first==0)
throw (b.first);
};
void U(P b)
{ if (b.second == "1, 2, 3, 4, 5, 6, 7, 8, 9" )
throw (b.second);
};
int _tmain(int argc, _TCHAR* argv[])
{
P x;
cin>>x.first;
cin>>x.second;
try
{
P x;
T(x);
}
catch (int exception)
{
std::cout << exception;
}
try{
U(x);
}
catch (const char* exception)
{
std::cout << "\n" << exception;
}
system("pause");
return 0;
}
我有以下输入:
0
1, 2, 3, 4, 5, 6, 7, 8, 9
和输出:
0
我想得到:
0
1, 2, 3, 4, 5, 6, 7, 8, 9
如何更改字符串输出的字符?
【问题讨论】:
-
代码具体有什么问题?你有什么意见?请注意,您正在捕获
const char*,但您正在抛出std::string。我不确定这是否应该工作。 -
你正在抛出一个
std::string,但你试图抓住一个const char* -
@SimonKraemer,@churill,是的,我确实想过,但我不知道字符串的走动,因为
string exception不正确 -
P x; T(x);将一个不同的x传递给T,而不是你用std::cin初始化的那个。在T中,您以b.first==0开头,但first成员未初始化,这意味着它具有未定义的行为。 -
下一个问题
std::cin >> x;将在第一个空白处停止读取。您需要使用std::getline来阅读整行。我还建议学习如何使用调试器来调查程序在运行时的状态。
标签: c++ exception constructor