我在学习 C 时一直在疯狂地研究。我一直在调试 C 程序,我认为我在这里遇到了一些重大问题。现在我有关键问题。我制作了一个虚拟程序,在一个语句中打印两个字符串,如下所示:
#include<stdio.h>
int main(int argc, char* argv[])
{
char *herp = "Derp";
char *derp = "Herp";
printf("Herp %s Derp %s\n", herp, derp);
return 0;
}
这按预期打印出来。我明白了
Herp Derp Derp Herp
所以,我想,让我通过做类似的事情来调试我自己的程序。我的程序中的以下行
printf("word is: %s and jumbled word is: %s\n", word, jumbleWord);
应该打印出类似的东西
Word is: word and jumbled word is: dowr
但它会打印出类似的东西
and jumbled word is: dowr
输出的第一部分去哪儿了?我需要能够在同一行上打印它们以进行调试。此外,像这样的声明不起作用的事实告诉我,正在发生非常奇怪的事情,我因为扯掉头发而秃顶。正如我链接的帖子所表明的那样,我最终想比较这些字符串值,但是如果 printf() 不能正常工作,我怎么能这样做呢?
我在下面发布了整个程序,这样你就可以看到一切发生的地方。我只是在学习如何使用指针。当我想弄乱一个单词时,我最初有两个指针指向同一个内存,但效果不太好!所以我解决了这个问题,得到了两个单独的内存空间,里面有我需要的单词。现在,我只是无法打印它们。鉴于以下代码,这一切都说得通:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_WORD_LENGTH 25
//Define global variables
int numWords;
//Preprocessed Functions
void jumblegame();
void readFile(char *[]);
void jumbleWord(char *);
void guess(char *,char *);
int main(int argc, char* argv[])
{
jumblegame();
return 0;
}
void jumblegame()
{
//Load File
int x = 5050; //Rows
char *words[x];
readFile(words);
//Define score variables
int totalScore = 0;
int currentScore = 0;
//Repeatedly pick a random work, randomly jumble it, and let the user guess what it is
srand((unsigned int)time(NULL));
int randomNum = rand() % numWords + 1;
char source[MAX_WORD_LENGTH + 1];
char jumble[MAX_WORD_LENGTH + 1];
strncpy(source, words[randomNum], MAX_WORD_LENGTH + 1);
strncpy(jumble, words[randomNum],MAX_WORD_LENGTH + 1);
jumbleWord(jumble);
guess(source, jumble);
//printf("Random word is: %s\n ", words[randomNum]);
//randomly jumble it
}
void readFile(char *array[5049])
{
char line[256]; //This is to to grab each string in the file and put it in a line.
int z = 0; //Indice for the array
FILE *file;
file = fopen("words.txt","r");
//Check to make sure file can open
if(file == NULL)
{
printf("Error: File does not open.");
exit(1);
}
//Otherwise, read file into array
else
{
while(!feof(file))//The file will loop until end of file
{
if((fgets(line,256,file))!= NULL)//If the line isn't empty
{
int len = strlen(line);
if (len > 0 && line[len - 1] == '\n') line[len - 1] = '\0';
array[z] = malloc(strlen(line) + 1);
strcpy(array[z],line);
z++;
}
}
}
fclose(file);
numWords = z;
}
void jumbleWord(char *word)
{
int wordSize = strlen(word) - 1;
//durstenfeld Implementation of Fischer-Yates Shuffle
int i;
int j;
char temp;
for(i = wordSize - 1; i > 0; i--)
{
j = rand() % (i + 1);
temp = word[j];
word[j] = word[i];
word[i] = temp;
}
}
void guess(char *word, char *jumbleWord)
{
printf("original word is: %s\n", word);
printf("jumbled word is: %s\n", jumbleWord);
printf("source is: %s and jumbled word is: %s\n", word, jumbleWord);
}
我认为此时大多数人会烧掉C并为自己吸得如此糟糕而扇耳光。但是,我将继续运输。所以让我为任何愚蠢的行为道歉,但请知道我已经花了很多时间可能真的很愚蠢并盯着这个。我很想说,“嘿,C 太愚蠢了,因为它不会按照我说的去做”。不幸的是,我无法相信这一点。我认为它正在做我告诉它做的事情,但我离这个问题太近了,看不出我做错了什么。
一如既往,感谢您的帮助。我最深的敬意,GeekyOmega