Reputation: 1536
I though setting up a veritable len
with strlen()
function to find the last char, print it, and then decrement it by 1. It is not working in my code:
#include <stdio.h>
#include <string.h>
#define SIZE 4
int main(void)
{
int index;
char wordToPrint[SIZE];
printf("please enter a random word:\n");
for (index = 0; index < SIZE; index++)
{
scanf("%c", &wordToPrint[index]);
}
int len = strlen(wordToPrint);
for (index = 0; index < SIZE; index++)
{
printf("%c", wordToPrint[len]);
--len;
}
return 0;
}
input is "nir"
output is:
??
r
What is wrong in the last block?
tnx
Upvotes: 1
Views: 8894
Reputation:
Lil' hack for fun :)
#include <stdio.h>
#include <stdlib.h>
#define LENGTH 32
int main(void)
{
// allocate a zero-filled buffer of LENGTH bytes
// we add LENGTH so that we start writing right *after* the buffer
char *word = LENGTH + calloc(LENGTH, 1);
// 0xFF will limit our buffer so that we do not write out of bounds
*(word - LENGTH) = 0xFF;
// order is important: we are decrementing the pointer and **then**
// reading a character from the standard input, we compare it to the
// line feed character so that we stop reading characters when return
// key is pressed
while ((*--word = fgetc(stdin)) != '\n' && *word != 0xFF);
printf("The word is: %s", word);
// tidy up!
free(word);
return 0;
}
Of course, this won't work as expected in "modern" systems, that implement line-buffered consoles rather than allowing the user to manually read one character at a time (albeit it can be implemented using platform-specific APIs.)
Upvotes: 0
Reputation: 53
This is the whole program, for your question.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strrev(char *); // Prototype
/* The following function is by me, to reverse a string, because strrev is not available in GCC */
char *strrev(char *str)
{
char *p1, *p2;
if (! str || ! *str)
return str;
for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2)
{
*p1 ^= *p2;
*p2 ^= *p1;
*p1 ^= *p2;
}
return str;
}
/*================================================================Begin Main======================================================================================*/
int main()
{
char sentence[100], rev_sentence[100], c;
int j = 0, i = 0, m = 0;
sentence[i] = ' '; // The first char in the sentence should be a space to reverse this first word
i++;
printf("Enter a sentence : ");
while((c = getchar()) != '\n')
{
sentence[i] = c;
i++;
}
sentence[i] = '\0';
printf("Reversed word is: ");
for(i = strlen(sentence) - 1 ; i >= 0; i = i - 1)
{
if(sentence[i] == ' ')
{
rev_sentence[j] = '\0'; // because strrev fun reverses string ntil it encounters a first \0 character
strrev(rev_sentence);
printf("%s ", rev_sentence);
for(m = 0; m < 100; m++)
rev_sentence[m] = 0;
j = 0;
continue;
}
rev_sentence[j] = sentence[i];
j++;
}
rev_sentence[j] = '\0';
}
This program reverses entire sentence, or a word if u enter just 1 word and press enter, hope u like it and understand it
Upvotes: 1
Reputation: 1291
write your code like this because at wordToPrint[len], len is the +1 then the last index of the wordToPrint[] array so its showing garbadge/null value
#include <stdio.h>
#include <string.h>
#define SIZE 4
int main(void)
{
int index;
char wordToPrint[SIZE];
printf("please enter a random word:\n");
for (index = 0; index < SIZE; index++)
{
scanf("%c", &wordToPrint[index]);
}
int len = strlen(wordToPrint);
for (index = 0; index < SIZE; index++)
{
--len;
printf("%c", wordToPrint[len-1]);
}
return 0;
}
Upvotes: 1
Reputation: 399949
C arrays index from zero.
Think about how this affects the relationship between the length of a string, and the index of the last character.
Also, your way of reading in the word is very strange, it should just be:
scanf("%s", wordToPrint);
or, better:
fgets(wordToPrint, sizeof wordToPrint, stdin);
There's no need to loop and read a character at a time. The above will give you different lengths depending on the amount of input.
The second suggestion will not stop at whitespace though, so if you go with that you should probably replace word
with line
for clarity.
Upvotes: 5
Reputation: 6684
Here is a working code based on the posted one:
#include <stdio.h>
#include <string.h>
#define SIZE 4
int main(void)
{
int index;
char wordToPrint[SIZE];
printf("please enter a random word:\n");
//Why you need a loop to read a word?
//for (index = 0; index < SIZE; index++)
//{
// scanf("%c", &wordToPrint[index]);
//}
scanf("%s",wordToPrint);
int len = strlen(wordToPrint);
//Modify the loop like this:
for (index = len; index >= 0 ; index--)
{
printf("%c", wordToPrint[len]);
}
printf("\n");//Add this line for clearing the stdout buffer and a more readable output.
return 0;
}
Note: its always a good practice to memset() or bzero() the array before using it.
Upvotes: 0
Reputation: 2770
In addition to what other posters are saying, you should probably consider giving and extra byte to the string:
char wordToPrint[SIZE + 1];
and then set
wordToPrint[4] = '\0';
In the case that someone inputs a 4 letter word (such as 'blue') your string will look like { 'b', 'l', 'u', 'e' } but with no room for a null character.
Strlen and other functions rely on finding a null value at the end.
Upvotes: 2
Reputation: 3947
In addition to the other answers, why use strlen() when you know that the word has SIZE chars?
Upvotes: 0
Reputation: 3103
int len = strlen(wordToPrint);
for (index = 0; index < SIZE; index++)
{
printf("%c", wordToPrint[len]);
--len;
}
return 0;
suppose you have word otto so
int len = strlen(wordToPrint);
will set len
to 4, but when you use it in printf("%c", wordToPrint[len]);
your array is getting out of bound wordToPrint[4]
where as the last index in array is wordToPrint[3]
as it starts from 0 index
Upvotes: 1
Reputation: 1767
This code is wrong:
int len = strlen(wordToPrint);
for (index = 0; index < SIZE; index++)
{
printf("%c", wordToPrint[len]);
--len;
}
Its printing chars from 4 to 1 but you want to print chars from 3 to 0.
You should do it this way:
for (index = len - 1; index >= 0; index--)
printf("%c", wordToPrint[index ]);
Upvotes: 0
Reputation: 477338
Reverse iteration needs to be offset by one:
Forward:
for (size_t i = 0; i != N; ++i) { putchar(word[i]); }
Backward:
for (size_t i = 0; i != N; ++i) { putchar(word[N - i - 1]); }
// ^^^^
This is because an array of length N
has valid indices in the range [0, N)
.
Upvotes: 2