【问题标题】:Questions about Strings in CC语言中关于字符串的问题
【发布时间】:2014-04-17 02:26:11
【问题描述】:

我还是 C 的新手,目前我对如何使用字符串有点困惑。现在我有两个函数:get_field() 和 get_line()。

typedef char f_string[MAX_CHARS+1] ;
typedef struct {
        int nfields ;                        
        f_string field[MAX_FIELDS] ;            
} csv_line ;



csv_line get_line() {
        csv_line toBe;
        f_string sField;
        toBe.nfields = 0;
        int r;
        while(r != '\n'){
                r = get_field(sField);
                printf("sField: %d\n", *sField);
                //toBe.field += *sField;
                if(r != EOF){
                        toBe.nfields += 1;
                }
                //sField = *"";
        }
        return toBe;

}


int get_field(f_string field) {
        char ch;
        ch = getchar();
        while(is_end_of_field(ch) == 0){
                field += ch;
                ch = getchar();
        }
        field += '\0';
        return ch;

我试图用它做的是从标准输入解析一行,直到它到达 字段结束条件(',''\n'或EOF)然后将该字符串添加到我认为是这些fstrings数组的“字段”中。 get_field() 似乎运行良好,但是当我尝试打印出我认为正在从 get_field 中编辑的 sField 时,我只得到一个 0。我在这里做错了什么? MAX_FIELDS 设置为 15,MAX_CHARS 设置为 20。当我尝试使用当前注释掉的行进行编译时出现的错误是...

error: invalid operands to binary + (have ‘char[15][21]’ and ‘int’)
error: incompatible types when assigning to type ‘f_string’ from type ‘char’

【问题讨论】:

  • 你对field += ch;的意图是什么?
  • 我想将字符添加到稍后将与 toBe.field 数组组合的字段字符串中。
  • 你应该使用field[i] = ch;之类的东西,因为get_field()field是一个指向char的指针。
  • 我建议在学习时不要使用数组类型定义,它们可能不直观并且会成为学习的障碍。

标签: c string function


【解决方案1】:
  1. while(r != '\n'){初始化之前,您正在使用r

  2. toBe.field += *sField; 应替换为 strcpy(toBe.field[i], sField);

  3. field += ch; 应该替换为field[i] = ch;,因为在get_field() 中,field 是指向char 的指针; field += '\0'; 应该同样修复。

顺便说一句,您的代码中存在许多潜在的缓冲区溢出问题,您可能还想修复它们。

【讨论】:

  • 我已经这样做了,但现在我还有其他一些问题,每当我尝试打印出“ch”时,它只会给我它的数值,还有我的“sField”字符串的值包含整个字段只包含第一个字符。
  • @BLU 如何打印ch?您应该使用printf("%c", ch); 之类的东西而不是printf("%d", c);,后者为您提供ch 的ASCII 值。
猜你喜欢
  • 2020-10-07
  • 1970-01-01
  • 2011-11-20
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多