为什么我在cin上发生了segfault? [英] Why am I getting a segfault on cin?

查看:211
本文介绍了为什么我在cin上发生了segfault?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个相当简单的练习(家庭作业),大部分工作,但有时在cin上的segfaults。这是相关的代码。

I am writing a fairly simple exercise (homework), and most of it works, however it sometimes segfaults on cin. Here is the relevant code.

int main()
{
  std::string str = "";
  std::cout << "Please select the desired operation:\n";
  std::cout << "(A): Generate Decompositions\n";
  std::cout << "(B): Generate Acceptable Compositions from S1.txt and S2.txt\n";
std::cout << "cout"; //debug statement
  std::cin >> str;
std::cout << "cin"; //debug statement
  std::cout << str;
  char resp = str.at(0);
std::cout << "resp"; //debug statement

...
}

I在 std :: cin>>>上获取segfault str (我知道这是因为什么debug语句输出)。但奇怪的是,我只有当我输入'b'时才会得到它。如果我输入'a',或任何以'a'开头的单词,它工作正常。如果我输入除a或b以外的任何字母,或以除a或b之外的任何其他字母开头的任何字母,它会退出(如它应该的那样)。但是如果我输入'b',或任何以'b'开头的单词,它的Segfaults。每一次。为什么?

I get a segfault on std::cin >> str (I know this because of what "debug statements" are output). But the weird thing is, I only get it when I input 'b'. If I input 'a', or any word starting with 'a', it works fine. If I enter any letter other than a or b, or anything starting with any other letter than a or b, it exits (as it's supposed to). But if I type in 'b', or any word starting with 'b', it Segfaults. Every single time. Why?

推荐答案


我知道这是因为debug语句输出

I know this because of what "debug statements" are output"

您发布的代码看起来很好。

The code that you posted looks fine.

由于您的输出语句没有<< endl 在结束时,一些输出可能仍然在segfault时缓冲写出 endl 直到输出被刷新,因此添加<< endl 很可能帮助您更接近崩溃的实际位置。

Since your output statements do not have << endl at the end, some of the output may still be buffered at the time of segfault. Writing out endl blocks until the output is flushed, so adding << endl is likely to help you get closer to the actual location of the crash.

这篇关于为什么我在cin上发生了segfault?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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