Reputation: 11
I need help rotating words so they output with the 1st letter at the end. I have a file called flip.txt
backpack
carpet
rotate
and i want to be able to enter ./RotateWord < flip.txt (in terminal) and it should output
ackpackb
arpetc
otater
I was able to get it to output the words with the 1st letter missing . How to i make it output the 1st letter at the end?
Heres my code
#include <stdio.h>
#define BUFFER_SIZE 81
int main(int argc, char **argv) {
char string[BUFFER_SIZE];
while(fgets(string, BUFFER_SIZE, stdin) > 0) {
int numChars = 0;
while(string[numChars] && string[numChars] != '\n')
++numChars;
int i;
for(i = 1; i < numChars; ++i){
if (string[i] == '\n'){
putchar(string[0]);
putchar('\n');
}
else {
putchar(string[i]);
}
}
putchar('\n');
fflush(stdout);
}
return 0;
}
Upvotes: 0
Views: 543
Reputation: 30926
You can use strcspn
to get rid of the \n
.
string[strcspn(string,"\n")]=0;
If you want to print the string in that way - do this two line. (You can merge it in one line too).
printf("%s",string+1);
printf("%c\n",string[0]);
The code will be
while(fgets(string, BUFFER_SIZE, stdin) != NULL) {
string[strcspn(string,"\n")]=0;
printf("%s%c\n",string+1,string[0]);
fflush(stdout);
}
The thing is as per your code the if
block is never executed. So you will never get the first character printed. The previous while loop
simply increments the variable as long as it doesn't meet the \n
. Then in the next loop you iterate over them < numChars
and then expect to see the \n
, which won't be the case now.
while(fgets(string, BUFFER_SIZE, stdin) != NULL) {
for(int i = 1; string[i]; ++i){
if (string[i] == '\n'){
putchar(string[0]);
putchar('\n');
}
else {
putchar(string[i]);
}
}
fflush(stdout);
}
Earlier you were putting \n
after every character that you print. It should be only after the last character.
fgets
returns char*
- in case of error it returns NULL
. So to check if fgets
is successful or not you should do a null check.
Upvotes: 1
Reputation: 57
In the for loop run till
for(i=1,i<=numChars,i++)
This is because the if statement does not get executed as the index does not reach the newline character. Thus the complete code is as follows:
#include <stdio.h>
#define BUFFER_SIZE 81
int main(int argc, char **argv) {
char string[BUFFER_SIZE];
while(fgets(string, BUFFER_SIZE, stdin) > 0) {
int numChars = 0;
while(string[numChars] && string[numChars] != '\n')
++numChars;
int i;
for(i = 1; i <= numChars; ++i){
if (string[i] == '\n'){
putchar(string[0]);
putchar('\n');
}
else {
putchar(string[i]);
}
}
//putchar('\n');
fflush(stdout);
}
return 0;
}
Also there is no need of extra
putchar('\n');
Upvotes: 0
Reputation: 2302
It it possible that you're not counting the final '\n' character when you
while(string[numChars] && string[numChars] != '\n')
++numChars;
?
If so, you never hit
if (string[i] == '\n'){
putchar(string[0]);
putchar('\n');
}
because your loop stops one early.
Upvotes: 1