Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/156.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 坏流中的异常_C++_Exception - Fatal编程技术网

C++ 坏流中的异常

C++ 坏流中的异常,c++,exception,C++,Exception,如果用户要输入字母而不是整数,则循环将变为疯狂。 我知道如何摆脱那个错误 cin.clear() and cin.ignore() 但我一直不明白为什么会这样。字符由0到255之间的整数表示。每个数字都是32位,足够整数变量处理..那么为什么流会失败呢 是否可以使用异常来测试此错误,我正在尝试理解异常,但无法为此编写代码。您可以将循环编写为: int var; while ( std::cin >> var ) { //do whatever you want to do

如果用户要输入字母而不是整数,则循环将变为疯狂。 我知道如何摆脱那个错误

cin.clear() and cin.ignore()
但我一直不明白为什么会这样。字符由0到255之间的整数表示。每个数字都是32位,足够整数变量处理..那么为什么流会失败呢


是否可以使用异常来测试此错误,我正在尝试理解异常,但无法为此编写代码。

您可以将循环编写为:

int var;
while ( std::cin >> var )
{
     //do whatever you want to do with var
}

如果输入的不是整数,则循环将中断。这意味着,如果您输入字母、标点符号、浮点数等,循环将退出,这意味着输入流中出现了错误。

是的,您可以告诉任何流使用

cin.exceptions(istream::failbit | istream::badbit);
尝试
{
INTA;
cin>>a;
}
捕获(istream::failure&e)
{
瑟尔
但是我不明白为什么会发生这种情况。一个字符由一个0到255的整数表示。每个数字都是32位,足以让整数变量处理。那么,为什么流会失败呢

规范中说,当您对int使用操作符>>时,它需要将输入解析为整数的文本表示形式(根据当前嵌入的区域设置,尽管对于int来说,这可能不太重要)。这意味着,除非您还使用io操纵器接受非默认基数(例如)根据定义,字母数字是不允许的

如果要接受任何字符并将其视为“短整数”的二进制表示形式,可以

 unsigned char uch;
 signed char   sch;

 std::cin >> uch;
 std::cin >> sch;
正如您正确预期的那样,这绝不会因为解析原因而失败(只有eof()、权限被拒绝、内存不足或其他技术故障…)


希望这解释了它们为什么会这样工作:


当然,流操作符>>也是可能的,但是不要-异常和流处理不能很好地结合在一起,这就是为什么它们在默认情况下没有被启用的原因。@Unaperson:你能更详细一点吗?@DeadMG尝试编写带异常的I/O-你会明白我的意思。@Unaperson:异常和流完美地结合在一起,并且r大型处理它们是完美的解决方案。但是当我们有需要处理的用户输入时,错误可以立即处理(生成错误消息,用户可以重复输入),因此不需要异常(当错误与处理分开处理时,异常工作(异常良好)。
 unsigned char uch;
 signed char   sch;

 std::cin >> uch;
 std::cin >> sch;
int a;
stream >> a; // I expect the stream to contain an integer in human readable form.

MyClass x;
stream >> x; // I expect the class to contain a serialize version of x;
char y;
stream.read(&y, 1); // Read a single byte into y

int  x = y;         // now convert the byte to an integer.
std::cout << "Enter a number\n";
int number;
while(!(std::cin >> number))
{
    std::cout << "That was not a number\n";
    std::cin.clear();
    std::cin.ignore();
}


// With exceptions:

  // That's too much work.
// If the read fails get out of here with an exception.
while(data >> x >> y >> z >> j >> q >> p >> src >> dst)
{
    doWork();
}
ExapndAndGrok();


// Handling the errors:

while(data >> x >> y >> z >> j >> q >> p >> src >> dst)
{
    doWork();
}
if (testDataStreamForSomeError(data)) // EOF is not an error.
{
    throw someException("The input failed");
}
ExapndAndGrok();