このコードの問題点は、ユーザーがコマンドラインでテキストを入力した後に実際に何も印刷されないことです。cで反転配列が印刷されません -
コードの目的は、ユーザーがファイル名の後にコマンドプロンプトを使用して入力する行数を受け入れることです。次に、ユーザは何かを入力して、逆にする。プログラムは、各行のユーザー入力を元に戻すことになっています。
例入力=大きな赤い犬
出力例=それは困難のようにあなたを思わ
#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 + '')'はあなたの考えをしません。 – aschepler
'strlen()'を使って入力行の長さを取得してみませんか? – Barmar
'strlen()'や 'strtok()'のようなCの標準文字列関数を使うことは許されていませんか?しかし、あなたは 'strcat()'と 'strncpy()'を使うことが許されていますか? – Barmar