c - C 中字符串处理的问题

标签 c string

我被困在一项 HW 作业中,我需要编写一个程序,将一堆英语单词(在输入 .txt 文件中以换行符分隔的列表中)转换成一堆 Pig Latin 单词 (到输出 .txt 文件中由新行分隔的列表中)。我已经非常接近了,但是我正在使用的 strncat 函数(字符串连接)函数以某种方式插入了一个新行,这确实丢弃了我正在打印到 stdout(现在用它来测试)。任何想法为什么会发生这种情况?这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STR_SIZE 100

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");

   //pStrPtr = pStr; 

   if(fileInPtr == NULL)                                //Check if file exists
   {
      printf("Failed");
      exit(-1); 
   }


   do                   //Cycles until end of text
   {
      fgets(str, 29, fileInPtr);                //Assigns word to *char

      str[29] = '\0';                           //Optional: Whole line

      convertToPigLatin(str, pStr); 
      fprintf(fileOutPtr, "%s", 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(pStr, cStr);
      strcat(pStr, ayStr);
   }  
   printf("%s", pStr);                       

 //  return pStrPtr; 
}

最佳答案

这段代码中有很多奇怪的地方,但您所问的问题是由 convertToPigLatin 中的 while 循环造成的。当 *strPtr != '\0' 循环时,\n 肯定不是 \0,因此您将其添加到 pStr.

现在剩下的代码,只是一些注释:

  • 使用strncat 复制一个字符是一种奇怪的用法。通常,人们会改用简单的字符分配(如 str1[i] = str2[j])
  • *strPtr++ 正在递增指针并取消引用它,但随后对取消引用的值不执行任何操作。你只需要 strPtr++ 就可以了。
  • 您可以使用 char str[] = "some string" 创建字符串文字。您不需要使用数组初始化语法。

那些是我没有详细阅读就跳出来的。祝你 future 的任务顺利。

编辑补充说,在这些情况下,使用调试器单步执行代码非常有值(value)。您会确切地看到添加换行符的位置。

关于c - C 中字符串处理的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17847090/

相关文章:

python - 使用 python 中的字符串索引从文件名返回文件扩展名

java - 如何在 Java 的构造函数中设置默认字符串格式?

string - 尝试仅显示一定数量的数字

java - 如何在 Java 中将一个字符串在某个索引处分成两部分并保留两部分?

c - 如何恢复被 sigwaitinfo/sigwait 挂起的线程?如何检查信号队列?

c - 是否有任何工具可以在运行时检测竞争条件并重写代码以避免将来出现它们

c# - 修剪 ServiceStack 模型的字符串

c - 多个 if 语句和 else if 之间有区别吗?

c++ - 嵌入式编程...一开始

c - 指向结构体的指针的二维数组(动态)