c - 为什么这个倒置句子算法不起作用?
问题描述
代码中有一些人类可读代码的注释:
#include <stdio.h>
#include <string.h>
#define SIZE 100 //size of the input array and output array
#define ACCUM_CHAR_SIZE 25 //size of the temp array
int main(){
char i[SIZE];
char acc[ACCUM_CHAR_SIZE];
char o[SIZE];
int it_l = 0, it_a = 0, it_r = 0;
//it_l is the iterator to the input sentence,
//it_a is the iterator to the temp array
//it_r is the iterator to the output sentence
printf("Enter a sentence:");
gets(i);
int len = strlen(i) - 1;
while(it_l <= len){
if(i[len - it_l] != ' '){
acc[it_a] = i[len - it_l]; //add letters to acc until space
it_a++;
}
else{
it_a -= 1;
//acc is reversed, I reversed it again to the output sentence
while(it_a >= 0){
o[it_r] = acc[it_a];
it_r++;
it_a--;
}
it_r += 1;
o[it_r] = 32; //put a space
it_a = 0; //reset the temp array
strcpy(acc, ""); //clear the acc
}
it_l++;
}
printf("%s", o);
}
该程序理论上看起来不错,但是在执行时,有时会打印垃圾值,仅打印一些单词或仅用垃圾值而不是空格反转一半的句子。
上面的程序是将每个单词保存到temp,然后将temp(存储单词时temp反转)返回到输出。但是,它失败了。
感谢您的帮助。
解决方案
至少存在三个问题。
第一个问题是您永远不会终止字符串o
要进行更改:
printf("%s", o);
进入
o[it_r] = '\0';
printf("%s", o);
第二个问题是您it_r
错误地递增。改变
it_r += 1;
o[it_r] = 32; //put a space
进入
o[it_r] = ' '; // Use ' ' instead of 32
it_r += 1;
第三个问题是你不处理输入的第一个单词(因为前面没有空格)。我会把这个问题留给你作为练习。
顺便说一句:不要gets
用于读取输入。改为使用fgets
。
推荐阅读
- javascript - 经典表情符号 unicode 列表
- java - 理解这个数独求解器的部分内容
- java - 如何为 ListView SecondActivity 创建 arrayList
- html - Angular - 防止禁用按钮上的点击事件
- python - 如何从 3d NumPy 数组中绘制单个像素值?
- python - Python PEP 是否按照提议/修改的方式实施,还是有回旋余地?
- svg - 如何从 PNG 创建 SVG
- python - os.listdir() 什么都不返回,甚至是一个空列表
- python - 从导入的文本文件数组输出总和、平均值和标准差
- python - Python,从另一个子文件夹导入子文件夹