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