所以,我想要做的就是将一个字符串从函数中的数组返回到 main() 函数中的一个变量。下面是我的功能。它基本上在一些文件中搜索一个词,并返回包含“START_ROOM”的文件的字符串名称:
char startPrompt()
{
//array of files
char* arrayFiles[7]={"Room1.txt", "Room2.txt", "Room3.txt", "Room4.txt", "Room5.txt", "Room6.txt", "Room7.txt"};
//used to store file that has START_FILE in it
char startFile;
int i;
for(i=0;i<7;i++)
{
//pointer to files
FILE *fPointer;
//prints files to output
char loadScreenOutput[800];
char* response[256];
fPointer=fopen(arrayFiles[i], "r");
//checks if the file doesn't exist
if(fPointer== NULL)
{
printf("Unable to open the file!\n");
}
//if file exists, do this.
else
{
while(!feof(fPointer))
{
fgets(loadScreenOutput, 800, fPointer);
if(strstr(loadScreenOutput, "START_ROOM"))
{
return *arrayFiles[i];
}
}
fclose(fPointer);
}
}
主要功能在这里:
int main()
{
char fileName;
//start the game with the start file
fileName=startPrompt();
printf("%s", fileName)
return 0;
}
然而,以上会导致分段错误。
如果我将 printf 更改为 printf("%c", fileName),我将得到文件的第一个字母,即“R”。
那么,我怎样才能简单地让它返回“Room1.txt”并将其存储在文件名中?我愿意更改 fileName 的变量类型,因为我猜这可能是问题所在。或者更改函数的返回类型,因为我猜这就是问题所在。
Overwise,我知道这段代码有效,因为如果我在函数内部使用 printf(),它将打印“Room7.txt”。
代码有点奇怪,但主要问题是您希望单个字符(即char
)保存“字符串”,即字符序列。C 中的字符串是由特殊值终止的字符序列0
;它们通常与指向字符串文字的指针一起使用,写为char* someStringValue = "ABC"
:
char* str = "ABC"; // str will point to a sequence of characters {'A','B','C',0 }
char c = 'X'; // c will hold a single character 'X';
printf("%s",str); // will print ABC
printf("%s",c); // will probably segfault because c is not a pointer to a sequence of characters, i.e. is NOT A POINTER
printf("%c",c); // prints X
c = *str; // assignes the first character of the sequence to which str points
printf("%c",c); // prints A
要更正您的程序,请编写:
char* startPrompt() // char* instead of char; char would be a single character
{
// static; otherwise the variable and its values go out of scope and become invalid once startPrompt has finished
static char* arrayFiles[7]={"Room1.txt", "Room2.txt", "Room3.txt", "Room4.txt", "Room5.txt", "Room6.txt", "Room7.txt"};
...
return arrayFiles[i]; // not *arrayFiles[i], which would be a single character
...
int main() {
char* fileName; // char*, not char
fileName=startPrompt();
printf("%s", fileName)
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句