Reputation: 41
I want my program to prompt the user for how many sentences they want to write and then enter those sentences. However, when I try entering the sentences, I keep getting errors. I tried using several different fucntions but all of them gave some kind of error. For example, right now I am trying to use fgets() and after I enter the first sentence it gives me a segmentation fault. Can someone tell me what is the best way to take input for a string with spaces and how to fix my problem?
int n;
char str[n][80];
printf("Enter number of lines: ");
scanf("%d", &n);
printf("Enter a sentecne: ");
for(int i = 0; i < n; i++){
fgets(str[i], 80, stdin);
printf("%s", str[i]);
}
Upvotes: 0
Views: 78
Reputation: 1089
you can use read function http://man7.org/linux/man-pages/man2/read.2.html
reading on the file descriptor 0 (standart input), a char *buffer to store your data, and a size_t size to read
there are several problems in your code
int n; // must have a value
int n = 10; // example, here your variable is initialized
you also don't check the return value of scanf
Upvotes: 1
Reputation: 409266
You define the array str
before you initialize n
. That means n
will have an indeterminate value (which will be seemingly random).
Move the input of n
to before you define str
.
Upvotes: 3