简体   繁体   English

为什么我在cin上遇到段错误?

[英]Why am I getting a segfault on cin?

I am writing a fairly simple exercise (homework), and most of it works, however it sometimes segfaults on cin. 我正在写一个相当简单的练习(家庭作业),并且大多数都有效,但是有时会在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 get a segfault on std::cin >> str (I know this because of what "debug statements" are output). 我在std::cin >> str上遇到了段错误(我知道这是因为输出了什么“调试语句”)。 But the weird thing is, I only get it when I input 'b' . 但是奇怪的是, 我只有在输入'b'时才能得到它 If I input 'a', or any word starting with 'a', it works fine. 如果我输入“ a”或任何以“ a”开头的单词,则可以正常工作。 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). 如果我输入a或b以外的任何字母,或以a或b以外的任何其他字母开头的任何东西,它就会退出(如预期的那样)。 But if I type in 'b', or any word starting with 'b', it Segfaults. 但是,如果我输入“ b”或任何以“ b”开头的单词,则会出现Segfaults。 Every single time. 每一次。 Why? 为什么?

I know this because of what "debug statements" are output" 我知道这是因为输出了什么“调试语句”

The code that you posted looks fine. 您发布的代码看起来不错。

Since your output statements do not have << endl at the end, some of the output may still be buffered at the time of segfault. 由于您的输出语句末尾没有<< endl ,因此某些输出可能仍会在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. 写出endl块,直到刷新输出为止,因此添加<< endl可能会帮助您更接近崩溃的实际位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM