我已经盯着这段代码看了很长一段时间,但我无法找出这段代码有什么问题以及如何修复它。我认为其中一个数组正在写入超过分配的内容。
调试器允许我编译,但是当我编译时,我得到:
Unhandled exception at 0x774615de in HW6_StringProcessing.exe: 0xC0000005: Access violation.
这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STR_SIZE 100
void convertToPigLatin (char * strPtr, char * pStrPtr);
int main(int argc, char *argv[])
{
char str[MAX_STR_SIZE];
char pStr[MAX_STR_SIZE];
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");
fprintf(fileOutPtr, "---------------\t\t\t\t----------------\n");
while(!feof(fileInPtr)) //Cycles until end of text
{
fscanf(fileInPtr, "%99s", str); //Assigns word to *char
str[99] = '\0'; //Optional: Whole line
convertToPigLatin(str, pStr);
//fprintf(fileOutPtr, "%15s\t\t\t\t%15p\n", str, pStr);
printf("%s\n", str);
}
system("pause");
}
void convertToPigLatin (const char * strPtr, char * pStrPtr)
{
int VowelDetect = 0;
int LoopCounter = 0;
int consonantCounter = 0;
char cStr[MAX_STR_SIZE] = {'\0'};
char dStr[] = {'-','\0'};
char ayStr[] = {'a','y','\0'};
char wayStr[] = {'w','a','y','\0'};
while (*strPtr != '\0')
{
if (*strPtr == 'a' || *strPtr == 'e' ||
*strPtr == 'i' || *strPtr == 'o' ||
*strPtr == 'u' || VowelDetect ==1)
{
strncat(pStrPtr, strPtr, 1);
VowelDetect = 1;
}
else
{
strncat(cStr, strPtr, 1);
consonantCounter++;
}
*strPtr++;
}
strcat(pStrPtr, dStr);
if (consonantCounter == 0)
{
strcat(pStrPtr, wayStr);
}
else
{
strcat(cStr,ayStr);
strcat(pStrPtr, cStr);
}
printf("%s\n", pStrPtr);
}