简体   繁体   中英

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. 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). 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?

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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