Reputation: 7145
I need to read in a bunch of strings without knowing in advance how many are there and print them as they are read. So I decided to use while(!feof(stdin))
as an EOF indicator.Here is my code:
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
int main(void)
{
char* str;
std::cout<<"\nEnter strings:";
while(!feof(stdin))
{
std::cin>>str;
std::cout<<"\nThe string you entered is"<<str;
}
return 0;
}
The above code for some reason says segmentation fault
after I enter the first string.Can someone suggest a fix for that.
Upvotes: 1
Views: 142
Reputation:
A segmentation fault occurs when an application tries to access a memory location that it isn't allowed. In your case the problem is that you are dereferencing a non-initialized pointer: char* str;
A possible solution would be change the pointer to an array, with a suitable size
Something like this may suffice:
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
int main(void)
{
char str[20];
cout<<"\nEnter strings:";
while(!feof(stdin))
{
cin.width(20); //set a limit
cin>>str;
cout<<"\nThe string you entered is"<<str;
}
return 0;
}
Upvotes: 1
Reputation: 16832
You need to allocate some memory for the string you are reading to go into.
All you have currently is a pointer on the stack to some random memory area, which means that as you read characters they will stomp all over other data, or even memory you aren't allowed to write to - which then causes a segfault.
The problem with trying to allocate some memory is that you don't know how much to allocate until the string is read in... (You could just say "300 chars" and see if it's enough. But if it isn't you have the same problem of data corruption)
Better to use C++ std::string
type.
Upvotes: 2
Reputation: 60037
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
int main(void)
{
std::string str[300];
std::cout<<"\nEnter strings:";
while(!std::cin.eof())
{
std::cin>>str;
std::cout<<"\nThe string you entered is"<<str;
}
return 0;
}
Should do the trick
Upvotes: 0
Reputation: 47770
str
is declared as char* str
, which means it isn't really a string (just a pointer to it, uninitialized BTW), and doesn't allocate any space for it. That's why it seggfaults. Since you program in c++, you can use
std::string str;
and it will work. Don't forget to #include <string>
.
Upvotes: 1
Reputation: 108986
str
is a pointer to char
. It doesn't point anywhere valid when you try to write there.
Try some form of new
in C++, or, better yet since you're coding C++, use std::string
.
Upvotes: 1