【发布时间】:2017-09-02 05:43:09
【问题描述】:
此代码的问题在于,在用户在命令行中输入一些文本后,它实际上并没有打印任何内容。
代码的目的是接受用户在文件名后通过命令提示符输入的行数。然后用户将输入一些东西来反转。该程序应该为每一行反转用户输入。
示例输入 = the big red dog
示例输出 = dog red big the
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define SIZE 80
char * reverseWords(char *string);
//argc is the count of cmd arguments.
//each command line argument is of type string
int main(int argc, char *argv[]){
//initialize local variables
int i;
int N;
char str[SIZE];
for(i = 1; i <argc; i++)
{
//set N equal to the users number in the command line
N = atoi(argv[i]);
}
if(argc != 2){//2 means that something is in the argument.
printf("ERROR: Please provide an integer greater than or equal to 0");
exit(1);//exit the program
}else if(N < 0){//We cant have a negative array size.
printf("ERROR: Please provide an integer greater than or equal to 0");
exit(1);//exit the program
}else{
for(i = 0; i < N; i++){
/*
fgets(pointer to array, max # of chars copied,stdin = input from keyboard)
*/
fgets(str,SIZE,stdin);
printf("%s", reverseWords(str)); //<---does not print anything....
}
}
return 0;
}
char * reverseWords(char *line){
//declare local strings
char *temp, *word;
//instantiate index
int index = 0;
int word_len = 0;
/*set index = to size of user input
do this by checking if the index of line is
equal to the null-character.
*/
for(int i = 0; line[i] != '\0';i++)
{
index = i;//index = string length of line.
}
//check if index is less than 0.
//if not we decrement the index value.
for(index; index != -1; index--){
//checking for individual words or letters
if(line[index] == ' ' && word_len > 0){
strncpy(word,line,word_len);
strcat(temp , (word + ' '));
word_len = 0;
}else if(isalnum(line[index])){
word_len == word_len+1;
}//end if
}//end loop
//copy over the last word after the loop(if any)
if(word_len > 0){
strncpy(word,line,word_len);
strcat(temp,word);
}//end if
line = temp;
return line;
}//end procedure
【问题讨论】:
-
temp未初始化且不指向任何内容,因此您无法将其传递给strcat。(word + ' ')不会像你想的那样做。 -
为什么不用
strlen()来获取输入行的长度呢? -
你不能使用C的标准字符串函数如
strlen()和strtok()吗?但是你可以使用strcat()和strncpy()? -
这是什么
word_len == word_len+1;?
标签: c arrays printf reverse fgets