最后一个扭转字符串的单词正在转移到新线上,为什么?
我正试图通过C中的字扭转字符串。到目前为止,我成功地颠倒了单词,但是有一个新的线问题,我不明白为什么会发生。 代码在下面。
#include <stdio.h>
void reverse_string(char input[], int start, int end)
{
char temp;
while (start < end)
{
temp = input[start];
input[start] = input[end];
input[end] = temp;
start++;
end--;
}
}
int main()
{
char input[100];
printf("Input > ");
fgets(input, 100, stdin);
int start = 0, end = 0;
while (input[end])
{
for (end = start; input[end] && input[end] != ' '; end++);
reverse_string(input, start, end - 1);
start = end + 1;
}
printf("%s", input);
return 0;
}
如果输入是“今天是晴天”。结果是
yadoT si a ynnu
.yad
我想要的是
yadoT si a ynnu .yad
如何编辑上面的代码,以便每个反向单词都在同一行上?
I'm trying to reverse a string word by word in C. So far, I succeeded in reversing words, but there is a new line issue I don't understand why happening.
The code is below.
#include <stdio.h>
void reverse_string(char input[], int start, int end)
{
char temp;
while (start < end)
{
temp = input[start];
input[start] = input[end];
input[end] = temp;
start++;
end--;
}
}
int main()
{
char input[100];
printf("Input > ");
fgets(input, 100, stdin);
int start = 0, end = 0;
while (input[end])
{
for (end = start; input[end] && input[end] != ' '; end++);
reverse_string(input, start, end - 1);
start = end + 1;
}
printf("%s", input);
return 0;
}
If an input is "Today is a sunny day.", The result would be
yadoT si a ynnu
.yad
What I want is
yadoT si a ynnu .yad
How should I edit the code above so that every reversed word will be on the same line?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如评论中所述,呼叫返回到
fgets
的字符串将包括终止的newline字符。由于Newline不是实际空间字符,因此它被认为是最后一句话的一部分。为了解决此问题,您可以删除该新线,如链接帖子中所示。另外(也许更简单),只需更改您的
输入[END]!=''
测试将检查任何 whitespace字符(s)的测试;isspace()
function (声明在“ ctype.h”标头文件中)将为您执行此操作。因此,只需更改循环的单行(空): /code>,这使您对代码的任何未来读者都更加清楚,您实际上打算了空循环主体,而不是犯错误式错误;它还可以防止对某些编译器的警告。另外,关于为什么我使用
(unsigned char)
在参数上施放到isspace
,请参见:我需要在打电话给toupper(),tolower()等人之前施放未签名的charAs mentioned in the comments, the string returned by the call to
fgets
will include the terminating newline character. As that newline isn't an actual space character, it is considered part of the last word. To deal with this, you could remove that newline, as indicated in the linked posts.Alternatively (and maybe much more simply), just change your
input[end] != ' '
test to one that checks for any whitespace character(s); theisspace()
function (declared in the "ctype.h" header file) will do this for you. So, just change that one-line (empty)for
loop to this:Note that I have changed your "null statement"
;
loop body to{}
, which makes it much clearer to any future readers of your code that you actually intended that empty loop body, rather than making a typo-style error; it also prevents warnings on some compilers. Also, on why I used the(unsigned char)
cast on the argument toisspace
, see: Do I need to cast to unsigned char before calling toupper(), tolower(), et al.?