1

can somebody say me what im missing?

int main() {
char eingabe[100];
cin >> eingabe;
eingabe[strlen(eingabe)]='\0';
cout << eingabe << endl;
}

But i get this: Segmentation fault

:(

8
  • Remove this unnecessary line: eingabe[strlen(eingabe)]='\0'; Commented Jun 28, 2014 at 11:41
  • 1
    Please just think about eingabe[strlen(eingabe)]='\0' for a minute. Commented Jun 28, 2014 at 11:42
  • What is your input string? Commented Jun 28, 2014 at 11:42
  • You know that by-definition of a null char terminated string, s[strlen(s)] is already 0, right? How do you think strlen() managed to determine its return value? And to answer the question, std::string is what you're missing. Commented Jun 28, 2014 at 11:42
  • Just use std::string and safe yourself the trouble. Your program will break if the input is more than 99 chars long. Commented Jun 28, 2014 at 11:45

1 Answer 1

5

If cin contains a line longer then 99 characters, the cin >> operator writes beyond the eingabe[] buffer end. This is wrong and likely to generate the segfault.

You may want to use the std::string class, rather then a char[] buffer.

If you have some good reason to use a char[100] buffer, then cin.getline(eingabe,100) is what you need.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.