Remove trailing newline character using fgets - c

I am making a program to read a file and determine if a word is a palindrome. I am running into an issue where the last token has a trailing newline and won't register as a palindrome.
Here is the file input:
leVel CompUtER Science theORY radar
And this is my code:
#include<stdio.h>
#include<string.h>
void palindrome(char str[]){
int length = strlen(str);
int i = 0;
int j = length - 1;
for(i = 0; i < length; i++){
if(str[i] != str[j]){
printf("String %s is not a palindrome.\n", str);
return;
}
j--;
}
printf("String %s is a palindrome.\n", str);
return;
}
int main() {
char line1[100];
fgets(line1, 100, stdin);
printf("%s", line1);
char *token;
token = strtok(line1, " ");
while(token != NULL){
printf("%s\n", token);
palindrome(token);
token = strtok(NULL, " ");
}
Thanks for the help!

If you are using strtok, then you can use " \n" as the delimiter and the newline will be taken care of.
int main() {
char line1[100];
fgets(line1, 100, stdin);
printf("%s", line1);
const char *delim = " \n";
char *token;
token = strtok(line1, delim);
while(token != NULL){
printf("%s\n", token);
palindrome(token);
token = strtok(NULL, delim);
}
...
}
Another great method to remove the newline is to use strcspn like this:
char line[1024];
fgets(line, sizeof line, stdin);
line[strcspn(line, "\n")] = 0; // removing newline if one is found

Why not just use fgetc and stop at the newline? You could also even just find the newline character in the string and assign '\0' to it, and it will be gone.

Related

Parsing tokens into char ** with user input fgets()

My problem is quite similar to the problem here: Trimming a trailing \0 from fgets() in C
However, the suggested solution buffer[strcspn(buffer, "\n")] = 0; as I am using char ** to store the tokens
Here's my code:
char str[1024];
fgets(str, 1024, stdin);
const char s[2] = " ";
char *token;
char ** token_arr = malloc(100 * sizeof(char*));
int pos = 0;
token = strtok(str, s);
while( token != NULL) {
token_arr[pos] = token;
printf( "%d %s\n", pos, token );
pos++;
token = strtok(NULL, s);
}
int i = 0;
while (token_arr[i]) {
printf("%d %s \n", i, token_arr[i]);
i++;
}
Input:
a b c d e
The printf in each loop is separated by a blank line, which I presume is due to the trailing \0 that is perhaps stored inside the token_arr.
How can I remove it?
Thanks a lot
ETA: What I meant it each print loop is printing an unintended extra blank line.
Contrary to gets(), fgets() keeps the newline that you typed in after your input.
Since the newline is not in your list of tokens it is kept as a part of the last token, hence the empty line.
just replace const char s[2] = " ";
with
const char s[3] = " \n";

Removing a word from a given string

I have been trying to write a code to remove a word from an inputted string as part of my homework. But the thing is the outputted "modified" string never really gets modified and it actually always outputs the inputted string. I'm new to strings so I don't have a perfect understanding of how the string.h library functions work.
#include<stdio.h>
#include<string.h>
int main(void)
{
char str[60], strtemp[60], word[10], * token;
printf("Enter the sentence: ");
gets_s(str);
printf("Enter the word to be deleted: ");
gets_s(word);
int i = 0;
token = strtok(str, " ");
while (token != NULL) {
if (!i && token != word)
strcpy(strtemp, token);
else if (token == word) {
token = strtok(NULL, " ");
continue;
}
else {
strcat(strtemp, " ");
strcat(strtemp, token);
}
token = strtok(NULL, " ");
i++;
}
strcpy(str, strtemp);
printf("Modified string: %s \n", str);
}
Add the following:
char *strremove(char *str, const char *sub) {
size_t len = strlen(sub);
if (len > 0) {
char *p = str;
while ((p = strstr(p, sub)) != NULL) {
memmove(p, p + len, strlen(p + len) + 1);
}
}
return str;
}
You should use the memmove() (written on your post's comment too.)
Reference: this thread of SO.

How to print words containing character c on spot n from a string using strtok()?

I'm inputting the string str and want to print all of its words that contain the inputted character c on the position n (so if n = 1, it's the first character). I'm trying to do this using strtok() but I'm getting a weird crash. Any tips?
int main()
{
char str[100]; gets(str);
while(getchar()!='\n'); ///so that n or c don't scan a newline in them
int n; scanf("%d",&n);
char c; scanf("%c",&c);
char* token = strtok(str, " ");
while (token != NULL) {
if(token[n-1]==c){
printf("%s\n", token);
}
token = strtok(NULL, " ");
}
return 0;
}
I inputted the following:
Hi i like mint
2
i
Then the program suddenly crashes with the message:
Problem.exe has stopped working...
That while loop didn't seem necessary. Also, instead of gets(), I used fgets(). I moved most of the declarations at the beginning of function. This code now works probably.
#include <stdio.h>
#include <string.h>
int main()
{
int n;
char c, str[100];
fgets(str, 100, stdin);
scanf("%d %c",&n, &c);
char* token = strtok(str, " ");
while (token != NULL) {
if(token[n-1] == c) {
printf("%s\n", token);
}
token = strtok(NULL, " ");
}
return 0;
}
Here is the link where I tested it: https://ideone.com/KQkRrG

Trying to read in two lines using fgets. Why is it only reading the first line?

I am trying to read in two lines using fgets, but only the first line is read and then returns a segmentation fault. I'm not sure what I would need to change for it to read in the second line. Any help would be appreciated!
int main(void)
{
char str[100];
char *word;
//First Line
fgets(str, 100, stdin);
printf("%s", str);
word = strtok(str," ");
printf("%s\n", word);
while(word != NULL)
{
word = strtok(NULL," ");
printf("%s\n", word);
}
//Second Line
fgets(str, 100, stdin);
printf("%s", str);
word = strtok(str," ");
printf("%s\n", word);
while(word != NULL)
{
word = strtok(NULL," ");
printf("%s\n", word);
}
return 0;
}
You got the order of function calls wrong in two parts of your code; Your are calling printf() after calling strtok() without checking for NULL. Fix it as follows:
int main(void)
{
char str[100];
char *word;
//First Line
fgets(str, 100, stdin);
printf("Printing entire string: %s\n", str);
word = strtok(str, " ");
printf("Printing tokens:\n");
while (word != NULL)
{
printf("%s\n", word);
word = strtok(NULL, " ");
}
//Second Line
fgets(str, 100, stdin);
printf("Printing entire string: %s\n", str);
word = strtok(str, " ");
printf("Printing tokens:\n");
while (word != NULL)
{
printf("%s\n", word);
word = strtok(NULL, " ");
}
return 0;
}
regarding:
word = strtok(str," ");
printf("%s\n", word);
while(word != NULL)
{
word = strtok(NULL," ");
printf("%s\n", word);
}
the function: strtok() can return NULL.
The result is the call to printf() will be trying to print a value from address 0.
That is what is causing the seg fault.
Suggest:
word = strtok(str," ");
while(word != NULL)
{
printf("%s\n", word);
word = strtok(NULL," ");
}

strtok with comma spaces and tab

So consider this string:
1,2.2, 3.5 ,6, 7.7
And i want to separate each number, so until now i try this:
void readuserinput(char *ch)
{
char* buffer;
buffer = strtok(ch, ",");
while (buffer) {
printf("%s\n", buffer);
buffer = strtok(NULL, ",");
while (buffer && *buffer == '\040')
buffer++;
}
}
But this ignored theTab and print the number 7.7 with tab before.
As you can see in strtok documentation you can specify multiple delimiters to it. So you don't have to manually deal with whitespaces. strtok will do that for you:
void readuserinput(char *ch)
{
ch = strtok(ch, ", \t");
while (ch)
{
printf("%s\n", ch);
ch = strtok(NULL, ", \t");
}
}

Resources