所以我得到了我的代码以成功将英语转换为猪拉丁语,但是当我将变量传递回main {}时,我只能以某种方式返回地址位置或某个十六进制或字符编号.我试图使用不同的转换说明符和所有内容,但由于某种原因,我无法让它输出字符串.该程序从输入txt文件读取,计算转换,然后打印到输出txt文件.让我知道你认为是什么问题.谢谢!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STR_SIZE 50
char * convertToPigLatin (char * strPtr, char * pLatinStr);
int main(int argc, char *argv[])
{
char str[MAX_STR_SIZE];
char pStr[MAX_STR_SIZE];
char *pStrPtr;
FILE *fileInPtr; //Create file name
FILE *fileOutPtr;
fileInPtr = fopen("pigLatinIn.txt", "r"); //Assign text to file
fileOutPtr = fopen("pigLatinOut.txt", "w");
if(fileInPtr == NULL) //Check if file exists
{
printf("Failed");
exit(-1);
}
fprintf(fileOutPtr, "English Word\t\t\t\tPig Latin Word\n", pStr);
fprintf(fileOutPtr, "---------------\t\t\t\t----------------\n", pStr);
do //Cycles until end of text
{
fscanf(fileInPtr, "%29s", str); //Assigns word to *char
str[29] = '\0'; //Optional: Whole line
pStrPtr = convertToPigLatin(str, pStr);
fprintf(fileOutPtr, "%15s\t\t\t\t%15p\n", str, *pStr);
} while(!feof(fileInPtr));
system("pause");
}
char * convertToPigLatin (const char * strPtr, char * pStrPtr)
{
int VowelDetect = 0;
int LoopCounter = 0;
int consonantCounter = 0;
char pStr[MAX_STR_SIZE] = {'\0'};
char cStr[MAX_STR_SIZE] = {'\0'};
char dStr[] = {'-','\0'};
char ayStr[] = {'a','y','\0'};
char wayStr[] = {'w','a','y','\0'};
pStrPtr = pStr;
while (*strPtr != '\0')
{
if (*strPtr == 'a' || *strPtr == 'e' || *strPtr == 'i' || *strPtr == 'o' || *strPtr == 'u' || VowelDetect ==1)
{
strncat(pStr, strPtr, 1);
VowelDetect = 1;
}
else
{
strncat(cStr, strPtr, 1);
consonantCounter++;
}
*strPtr++;
}
strcat(pStr, dStr);
if (consonantCounter == 0)
{
strcat(pStr, wayStr);
}
else
{
strcat(cStr,ayStr);
strcat(pStr, cStr);
}
//printf("%s\n", pStr);
return pStr;
}
Run Code Online (Sandbox Code Playgroud)
您pStr将从convertToPigLatin函数返回局部变量.此变量使用的存储在函数返回时被释放,并且在函数返回后不再有效(并且可能被下一个函数调用覆盖).然而,这并不重要,因为你实际上并没有在任何时候使用它.在main(),你正在做pStrPtr = convertToPigLatin(str, pStr);分配pStrPtr转换字符串的(现在无效)地址,但是当你调用时printf(),你传递它str(原始字符串)和*pStr(char[]从未初始化或使用过的数组的第一个字符).最重要的是,你传递给的格式说明符printf()是%15s和%15p,那么你作为第二个变量传递的单个字符是printf()什么?你告诉printf()它它是你想要显示的指针.
我从阅读中看到的问题快速列表:
fprintf()显示表头,每个都有一个未使用的额外参数(无害).str[29] = '\0',fscanf()将为你获得的字符串以空值终止,并且你的缓冲区大于此.convertToPigLatin(),您立即丢弃传入的指针pStrPtr,然后再也不会再触摸该变量.strncat()复制一个字节?dStr,ayStr和wayStr,而有效的,是奇数.(为什么不char *dStr="-", *ayStr="ay", *wayStr="way"呢?convertToPigLatin()convertToPigLatin()