c - 颠倒句子中单词顺序的问题
问题描述
我想逐行阅读 inputtext.txt 并反转每行中的单词顺序并将它们打印出来(输入:hello world,输出:world hello)。使用此代码,我的输出全部混乱,并且出现运行时错误#2,说我的数组“字符串”周围的堆栈已损坏。我尝试在每次 while 循环迭代后将字符串重置为 null,但我仍然得到相同的错误。有没有人有任何建议来摆脱运行时错误或帮助代码更顺畅地运行?
int main() {
FILE *inp,*outp; //file input and output
int i,wordcount; //define counter variables
int k = 0,j=0;
char string[200]; //define string to scan sentence into
char words[20][20]; //2D string for each word in the sentence
inp = fopen("inputtext.txt", "r");
outp = fopen("output.txt", "w");
if (inp == NULL) {
printf("File not found.\n");
}
else {
while (!feof(inp)) {
fgets(string, 1000, inp);
printf("GOT SENTENCE\n");
for (i = 0; string[i] != '\0'; i++) {
if (string[i] == ' ') {
words[k][j] = '\0';
k++;
j = 0;
}
else
{
words[k][j] = string[i];
j++;
}
}
words[k][j] = '\0';
wordcount = k;
for (i = wordcount; i >= 0; i--) {
printf("%s ", words[i]);
}
printf("\n\n");
}
}
return 0;
}
解决方案
以下建议的代码:
- 干净地编译
- 正确检查错误
- 正确输出错误消息到
stderr
- 执行所需的功能
- 正确限制输入的最大长度
- 假设输入文件中没有超过 199 个字符的行
- 最小化函数的次数:
strlen()
被调用 - 实际上将反转的句子写入输出文件
现在,建议的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *inp,*outp; //file input and output
int wordcount; //define counter variables
int k = 0;
int j = 0;
char string[200]; //define string to scan sentence into
char words[20][20]; //2D string for each word in the sentence
inp = fopen("inputtext.txt", "r");
if( !inp )
{
perror( "fopen to read: inputtext.txt failed" );
exit( EXIT_FAILURE );
}
outp = fopen("output.txt", "w");
if( !outp )
{
perror( "fopen to write: output.txt failed" );
// cleanup
fclose( inp );
exit( EXIT_FAILURE );
}
size_t strLength = strlen( string );
for (size_t i = 0; i < strLength; i++)
{
// remove any trailing newline
string[ strspn( string, "\n" ) ] = '\0';
printf("GOT SENTENCE\n");
for (size_t i = 0; i < strlen(string); i++)
{
if (string[i] == ' ')
{
words[k][j] = '\0';
k++;
j = 0;
}
else
{
words[k][j] = string[i];
j++;
}
}
words[k][j] = '\0';
wordcount = k;
for ( int i = wordcount; i >= 0; i--)
{
printf("%s ", words[i]);
fprintf( outp, "%s ", words[i] );
}
printf("\n\n");
fprintf( outp, "\n" );
}
return 0;
}
推荐阅读
- reactjs - 如何使用 react-i18next Trans 组件编写默认翻译,即使用插值变量时有效的 JSX?
- vue.js - 带有本地存储密码的问题路由器
- ios - 检查 Firebase 动态链接配置
- python - AttributeError:模块没有属性“RegisterShape”
- c# - SyncFusion SfRichTextEditor 不返回使用 Prism、Xamarin.Forms 在 Android 上编辑的文本
- visual-studio-code - 如何更改材质主题文本颜色
- cypress - 如何在 cypress 中测试视频文件上传?
- amazon-cloudformation - 如何使用 CDK 修改 EKS 的默认容量实例角色?
- ggplot2 - 在ggplot中使用给定的最大和最小x值创建一个平滑图
- java - 如何为提议的 Java 语言特性提供反馈?