Need assistance with fgets

I'm building a shell (as an exercise for school), and I receive a segmentation fault when I use fgets as following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main() {
	char userCommand[MAXLENGTH];
	list<varType> variables;
	stack<string> dirStack;
	vector<string> command;
	list<jobType> jobs;

	while (1) {
		userCommand[0] = '\n';
		
		while (userCommand[0] == '\n') {
			cout << "smash > ";
			userCommand[0] = '\n'; 
			fgets(userCommand, MAXLENGTH, stdin);
		}
...
}


What am I doing wrong?
Thanks.
Last edited on
¿why are you using fgets() instead of std::getline (or std::istream::getline()) ?

I don't see anything wrong with your code, but it looks a little obfuscated.
¿what is the value of MAXLENGTH?
it works well in my test.

[root@localhost cpp]# cat fgets.cpp
#include<iostream>
#define MAXLENGTH 500
int main() {
char userCommand[MAXLENGTH];
userCommand[0] = '\n';
if (userCommand[0] == '\n') {
std::cout << "smash > ";
userCommand[0] = '\n';
fgets(userCommand, MAXLENGTH, stdin);
std::cout<<userCommand<<std::endl;
}
}
[root@localhost cpp]# gcc fgets.cpp -o fgets -lstdc++
[root@localhost cpp]# ./fgets
smash > ebay.com
ebay.com


fgets is faster than std::getline :P
Thanks for the help, but I found the mistake in a location further in the code.
I didn't think it could be there because I tried to figure out where the mistake is by printing things, and fgets was the only command it couldn't pass. I don't really understand how it happened.
Topic archived. No new replies allowed.