这是我向后打印字符串中每个单词的源代码。但是这段代码只是向后打印第一个单词而不是整个字符串。在向后打印第一个单词后,它会生成向后打印的第一个和第二个单词的图案。如果使用while而不是if,则会生成无限循环。
// Print an Entered String Backwards
#include <stdio.h>
#include <string.h>
int main()
{
int j,i;
char str[100];
printf("Enter String\n");
gets(str);
printf("\nString in Reverse Order\n");
i=0;
while(str[i]!='\0')
{
if(str[i]==' ')
{
for(j=i-1;j>=0;j--) //Loop starts from last char and decrements upto 0th char
printf("%c",str[j]);
printf(" ");
}
i++;
}
}
答案 0 :(得分:2)
请勿使用gets
。它不安全,已被弃用。请改用fgets
来读取输入字符串stdin
。现在,要向后打印字符串中的每个单词,您需要更改while
循环。
#include <stdio.h>
int main(void)
{
int i, j;
char str[100];
printf("Enter String\n");
// fgets reads one less than sizeof(str), i.e., 99
// characters from stdin and stores them in str array.
// it returns when a newline is input which it stores in
// the the array and then appends a terminating null byte
// to mark the end of the string
fgets(str, sizeof str, stdin);
printf("\nString in Reverse Order\n");
i = 0;
while(str[i] != '\0')
{
if(str[i] == ' ' || str[i] == '\n')
{
// the loop condition checks for either the
// start of the string or a whitespace since
// since these two cases demarcate a word from
// other words in the string
for(j = i - 1; j >= 0 && str[j] != ' '; j--)
printf("%c", str[j]);
printf(" ");
}
i++;
}
// output a newline to flush the output
printf("\n");
return 0;
}
答案 1 :(得分:0)
您评论的循环不应该在第0个字符处结束,但应该到达最后一个空白区域(如果有的话)。
//Print an Entered String Backwards
#include<stdio.h>
#include<string.h>
int main()
{
int j,i; int lastWhiteSpace = 0; //there were no white spaces
char str[100];
printf("Enter String\n");
gets(str);
printf("\nString in Reverse Order\n");
i=0;
while(str[i]!='\0')
{
if(str[i]==' ')
{
for(j=i-1;j>=lastWhiteSpace;j--) //Loop starts from last char and decrements upto the character after the last white space
printf("%c",str[j]);
printf(" ");
lastWhiteSpace = i + 1; //the character after this white space
}
i++;
}
//later edit
for(j=i-1;j>=lastWhiteSpace;j--)
printf("%c",str[j]);
printf("\n");
}
答案 2 :(得分:0)
每次将内循环测试为零时,每次都会打印到字符串的开头。你需要测试直到找到最后的空间。 对于内循环
这样的东西int lastSpace = 0, i = 0, j = 0;
while(str[i] != '\0')
{
if(str[i] == ' ')
{
for(j = i-i; j>= lastSpace; j++)
{
printf("%c", str[j]);
}
lastSpace = i;
}
i++;
}
答案 3 :(得分:0)
无需在单循环中进行双循环。
#include<stdio.h>
#include<string.h>
int main()
{
int j,i, len;
char str[100];
clrscr();
printf("Enter String\n");
gets(str);
printf("\nString in Reverse Order\n");
i = strlen(str) - 1;
while(i > -1)
{
printf("%c",str[i--]);
}
}
答案 4 :(得分:0)
#include<stdio.h>
#include<string.h>
int main()
{
int j,i, len;
char str[100];
char temp[20];
clrscr();
printf("Enter String\n");
gets(str);
printf("\nString in Reverse Order\n");
i = 0;
len = 0;
j = 0;
while(str[i] != '\0')
{
if(str[i] != ' ')
temp[j++] = str[i];
if(str[i] == ' ')
{
temp[j] = '\0';
len = strlen(temp);
while(len > -1)
{
printf("%c", temp[len--]);
}
printf(" ");
len = 0;
j = 0;
}
i++;
}
temp[j] = '\0';
len = strlen(temp);
printf(" ");
while(len > -1)
{
printf("%c",temp[len--]);
}
}