I am trying to read in input from a user, and then tokenize each word and put each word into an array of strings. At the end, the contents of the array are printed out for debugging. My code is below.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int MAX_INPUT_SIZE = 200;
volatile int running = 1;
while(running) {
char input[MAX_INPUT_SIZE];
char tokens[100];
printf("shell> ");
fgets(input, MAX_INPUT_SIZE, stdin);
//tokenize input string, put each token into an array
char *space;
space = strtok(input, " ");
tokens[0] = space;
int i = 1;
while (space != NULL) {
space = strtok(NULL, " ");
tokens[i] = space;
++i;
}
for(i = 0; tokens[i] != NULL; i++) {
printf(tokens[i]);
printf("\n");
}
printf("\n"); //clear any extra spaces
//return (EXIT_SUCCESS);
}
}
After I type in my input at the "shell> " prompt, gcc gives me the following error:
Segmentation fault (core dumped)
Any idea as to why this error is happening? Thanks in advance for your help!
char tokens[100];
This declaration should be array of array of characters(two dimensional character array) to hold Multiple strings
char tokens[100][30];
//in your case this wont work because you require pointers
//while dealing with `strtok()`
USE
Array of character pointers
char *tokens[100];
This is also wrong
printf(tokens[i]);
You should use printf with format specifier %s while printing string.
change like this
printf("%s", tokens[i]);
Related
So I have this super simple C code here taking a user input and prints it out followed by a "T-Plus" while loop. In this case I chose a random name for testing "whoa", but the while loop is not called. My question is, why does the "T-Plus: %d\n" while loop print not be called after the printf() function?:
#include <stdio.h>
char getString();
void tcount(void);
int main(void)
{
tcount();
}
void tcount(void)
{
// class scanf user input
printf("%s", getString());
int i = 1;
do
{
printf("T-Plus: %d\n", i);
i++;
} while( i < 51 );
}
char getString()
{
char name;
printf("Please a string name: \n");
scanf("%s", &name);
return name;
}
Now when I run it, this becomes the output:
$ ./namecount
Please a string name:
whoa
but the T-Plus: string does not get called.
I see two issues here:
1) In function getString() you are trying to read/scan a string in a char, you need memory to store the string and a terminating char, so you can use either of these two ways
Use a char array e.g. char name[50]; or
Use a char pointer and
allocate memory using malloc e.g.
char *p_name = malloc(sizeof(char)*50);
2) You are then trying to return this string which is stored in local variable (which would get destroyed as soon as function ends) so you should use the second approach (use malloc) and return the pointer.
So your code would look like:
#include <stdio.h>
#include <stdlib.h>
char * getString();
void tcount(void);
int main(void)
{
tcount();
}
void tcount(void)
{
// class scanf user input
char *p_name = getString();
printf("%s", p_name);
free(p_name);
int i = 1;
do
{
printf("T-Plus: %d\n", i);
i++;
} while( i < 51 );
}
char *getString()
{
char *p_name = malloc(sizeof(char)*50);
printf("Please a string name: \n");
scanf("%s", p_name);
return p_name;
}
Above answer did not work, Okay so I've edited the code like this, it compiles fine. But raises a segmentation fault though.
#include <stdio.h>
#include <stdlib.h>
char * getString();
void tcount(void);
int main(void)
{
tcount();
}
void tcount(void)
{
// class scanf user input
char *name = getString();
printf("%s", name);
free(name);
int i = 1;
do
{
printf("T-Plus: %d\n", i);
i++;
} while( i < 51 );
}
char * getString()
{
char *p_name[50];
printf("Please a string name: \n");
scanf("%49s", (char *) &p_name);
return *p_name;
}
When the program is run, it asks for your input but still raises a Segmentation fault (core dumped).
I have to get the third word in a string and wanted to use strtok. Now, the first printf works but after that I get a Seg Fault. So tokenizedString = strtok(NULL, " "); must be causing the issue, right?
Just for context: I'm looking for the third word in a string and there can be as many spaces as possible between the words.
#include <string.h>
#include <stdio.h>
char *tokenizeString(char *userCommand)
{
char *tokenizedString;
int counterForToken;
tokenizedString = strtok(userCommand, " ");
for(counterForToken = 0; counterForToken != 3; counterForToken++)
{
printf("%s\n", tokenizedString);
tokenizedString = strtok(NULL, " ");
if(tokenizedString == NULL)
{
break;
}
}
printf("%s\n", tokenizedString);
return tokenizedString;
}
int main(void)
{
char userCommand[255] = {0};
fgets(userCommand, sizeof(userCommand), stdin);
tokenizeString(userCommand);
}
Now, the first printf works but after that I get a Seg Fault. So tokenizedString = strtok(NULL, " "); must be causing the issue, right?
No, that is very poor correlation. The issue is in fact in the second call to printf. You can pass it tokenizedString when tokenizedString == NULL. The format specified %s is specified to expect a valid pointer to the first character of a zero terminated array of characters. Passing it NULL is illegal and leads to undefined behavior (causing a crash for instance). The fix is simple: check for a null pointer value. And the same applies to the first iteration of the loop, of course
char *tokenizeString(char *userCommand)
{
char *tokenizedString;
int counterForToken;
tokenizedString = strtok(userCommand, " ");
for(counterForToken = 0; counterForToken != 3 && tokenizedString != NULL; counterForToken++)
{
printf("%s\n", tokenizedString);
tokenizedString = strtok(NULL, " ");
}
if(tokenizedString != NULL)
printf("%s\n", tokenizedString);
return tokenizedString;
}
I'm in a beginner CS class learning C and we were tasked with coding a function to find string length using only string pointers. I have the following code:
#include <stdio.h>
int strlength(char* str);
int main() {
char *str;
int comp;
printf("Please enter the string: ");
scanf("%s", str);
printf("The length of the string is: %d\n", strlength(str));
return 0;
}
int strlength(char *str) {
int length = 0;
while(*str != '\0') {
length++;
str++;
}
return length;
}
I'm not really sure where I'm getting a segmentation fault. I've tried making a second pointer in the strlength function that equals str and incrementing that, but that also gives me a segmentation fault. Any insight would be appreciated!
char *str;
int comp;
printf("Please enter the string: ");
scanf("%s", str);
You should allocate memory in heap ( with malloc ) for *str before scanf. If you dont want to use malloc change it to char[number] so it can allocate memory in stack instead of heap
what i want to do is take a big input(read till users press enter(\n) ) and then call a function that puts the first word of this input(read till ' '). My problem is that even though it looks pretty simple it also has 2 extra allien characters in it. This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void findChoise(char *input, char *choise);
int main()
{
char choise[12];
char input[300];
printf("give me the input: ");
gets(input);
printf("%s\n", input);
printf("%s%d\n", "length of input: ", strlen(input));//for checking
findChoise(input, choise);
printf("%s%d\n", "length of output: ", strlen(choise));//for checking
printf("%s\n", choise);
return 0;
}
void findChoise(char *input, char *choise)
{
int i=0;
while(input[i] != ' ')
{
choise[i] = input[i];
i++;
};
}
What you have already done is very close. You are just missing the null character at the end of the string ("\0"). I have cleaned up your code a little bit and fixed somethings. Please read through it and try and understand what is going on.
Main things to note:
All strings are arrays of characters and terminates with a null character "\0"
When you declare buffers(input and choice), try to make them a power of 2. This has to due with how they are stored in memory
Avoid using gets and try scanf instead
#include <cstdio>
void findChoice(char*, char*);
int main() {
char choice[16];
char input[512];
scanf("%s", input);
findChoice(choice, input);
printf("%s", choice);
return 0;
}
void findChoice(char* input, char* choice) {
int i = 0;
while(input[i] != ' ') {
choice[i] = input[i];
++i;
}
choice[i] = '\0';
}
You also need to write a null character to end the choise string:
void findChoise(char *input, char *choise)
{
int i=0;
while(input[i] != ' ')
{
choise[i] = input[i];
i++;
}
choise[i] = 0;
}
also don't use gets:
fgets(input, sizeof(input), stdin);
and use %zu to print size_t:
printf("%s%zu\n", "length of input: ", strlen(input));
#include <stdio.h>
#include <string.h>
int main()
{
char s[15];
int i,j,n,*str;
printf("Enter a string");
scanf("%s",str);
n=strlen(str);
for(i=0;i<n;i++)
{
str[n]=str[0];
for(j=0;j<n;j++)
{
str[j]=str[j+1];
}
str[n]='\0';
printf("\n %s",str);
}
return 0;
}
this program gives me all possible rotations of string
can anyone explain str[n]=str[0] and str[j]=str[j+1] meaning
instead of taking n=strlen(s) can we use n=strlen(str)
plz explain
This rotates the string. The way it does so is by moving the first character to the last place by doing str[n] = str[0] (str[n] is the string-terminating null character '\0', then shifting the whole string down one (str[j] = str[j+1]), then replacing the null at the end (str[n]='\0').
This code would, if it were using s, cause a buffer overrun if the string is longer than 14 characters. However, there's also a logic error in the code: it should be either initializing str (as a char* not int*) or scanning into s with a length bound. For instance:
scanf("%14s", s);
or
str = (char*)malloc(500);
scanf("%500s", str);
instead of taking n=strlen(s) can we use n=strlen(str)
Actually, since str is an int-pointer that is not initialized anywhere, all uses of str should be replaced by s (it's probably just a typo).
#include <stdio.h>
#include <string.h>
int main()
{
char s[15];
char tmp_var;
int i,j,n,*str;
printf("Enter a string");
scanf("%s",str);
n=strlen(str);
for(i=0;i<n/2;i++)
{
tmp_var = str[i];
str[i] = str[n-i];
str[n-i] = tmp_var;
}
printf("\n Rotated String is %s \n",str);
return 0;
}