【问题标题】:How to correctly add characters to a C String in C Language?如何正确地将字符添加到 C 语言中的 C 字符串?
【发布时间】:2020-02-18 23:38:43
【问题描述】:

目前我正在编写一个可以遍历文本文件并分析每个字符的程序。如果一个字符是字母数字和有效标识符,我希望能够将该字符添加到字符串中。 我目前的代码是这样的:

char final[256]={'\0'}; 
unsigned int len = 0;
static int current = ' ';
static int temp = ' ';

if(isalpha(current)){
   final[0]=current;
   len = 1;
   for (temp = fgetc(file); isalnum(temp) || temp == '_';){
      for(int i = len; i <= len; i++){
      final[i] = temp;
      len++;
  }
}

final[len] = '\0';

我以目前的方式解决这个问题是否正确?您可以将字符添加到 C 中字符串的索引位置吗?

【问题讨论】:

  • 你可以,但我完全不清楚你为什么要迭代两次。内部循环似乎不正确;如果 len 和 i 都在递增,它似乎永远不会终止。
  • 对于初学者来说,您只需要调用一次fgetc()。第二个for() 将“永远”运行,因为您在每次迭代中都在不断增加条件......基本上您的代码是一团糟。
  • 看来你的想法是对的;不确定 if-for-for 是正确的方法。应该可以在O(n) 中做到这一点。
  • @Amor Diaz 目前尚不清楚您要做什么。您能否展示一个输入数据和结果数据的示例。
  • 不,等等。它甚至不会编译,因为 file 没有被初始化,即使它不会运行,因为 isalpha(' ') 是 0。

标签: c fgetc


【解决方案1】:

代码本身很简单。

char final[256];
unsigned int len = 0;

final[len] = fgetc(file); //we read the character but do not "approve" it.
//while (!isalpha(final[len])) final[len] = fgetc(file); //uncomment if you want to read the file until a valid identifier begins. Also it's barely an example: it lacks EOF check.

if(isalpha(final[len])){
   len = 1; //We "approve" the first character
   while ( isalnum( final[len] = fgetc(file) ) || final[len] == '_') //In C, conditions are checked left to right so if isalnum()==0 we check for '_' with correctly updated final[len] value.
      len++; //We "approve" the next character;
  }
}

final[len] = 0; //The last character has been read but not "approved" so we overwrite it with null-term.

关于第二个问题...是的,您可以将字符添加到索引位置。但它必须是最后一个位置,否则它将覆盖现有位置。如果要插入一些字符,请先使用memmove()函数。

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-09
    • 2021-12-30
    • 2023-03-17
    • 2017-06-28
    • 1970-01-01
    相关资源
    最近更新 更多