【问题标题】:Getting ^D at the end of string in c在c中的字符串末尾获取^D
【发布时间】:2015-02-09 21:59:15
【问题描述】:

所以我有一个周五的家庭作业要做,我很难弄清楚为什么会发生这种情况。代码如下:

while(curVal < length)
{
     code[word][wordVal] = input[curVal];
     if(input[curVal + 1] == 32) //Is the current char in the input a space
     {
          word++;
          curVal++;
          wordVal = -1;
     }
     curVal++;
     wordVal++;
}

在此之后,我在 ncurses 窗口中将其打印出来。对于输入“Lucas is great”,输出为:

     Lucas^D
     is
     great

我遇到的问题不是打印“Lucas”而是打印“Lucas^D”。如果有人了解我的代码在做什么并且可以帮我修复它,我将不胜感激。

【问题讨论】:

  • word++;前需要加code[word][wordVal+1] = 0;
  • 无关:如果你想将某个字符与空格字符进行比较,直接进行即可。 ' ' 是空格字符,就像'A' 是字母A 字符,所以if( input[curVal + 1] == ' ')

标签: c variable-assignment


【解决方案1】:

C 中的字符串由一个字符数组组成,最后一个 NUL 字符。 NUL 字符可以写为'\0'。如果您忘记将 NUL 字符放在字符串的末尾,则可能会发生各种不好的事情,包括打印垃圾字符和/或使程序崩溃。

所以你有两个选择。你可以在开始之前用 NUL 字符填充整个数组

memset( code, '\0', sizeof(code) );

或者您可以在找到字符串结尾时插入 NUL 字符。

 if(input[curVal + 1] == ' ') //Is the current char in the input a space
 {
      code[word][wordval] = '\0';
      word++;

【讨论】:

    【解决方案2】:

    代码没有使用'\0' 正确终止字符数组以使数组成为字符串。因此会导致后续打印出错 - 可能是未定义的行为。

    应在每个 code[word][wordVal] 赋值之后添加终止空字符'\0'

    code[word][wordVal] = input[curVal];
    // add
    code[word][wordVal  + 1] = '\0';
    

    将其添加到 if(input[curVal + 1] == 32) 块中,如果 curVal &lt; length 在遇到空格之前变为 false,则存在未设置的风险。

    【讨论】:

      【解决方案3】:

      当您将单词从input 复制到code 时,需要以零结尾(C 字符串以额外的零字节结尾):

      code[word][wordVal] = input[curVal];
      if (32 == input[curVal]) {
            // The character we just read was a space.
            // Transform it into a terminator.
            code[word][wordVal] = 0x0;
            wordVal = 0; // Prepare to write at first character...
            word++; // ...of next word.
       } else {
           wordVal++; // Next character
       }
       curVal++; // Next input byte
      

      那么当你到达输入的末尾时,你还必须终止最后一个单词。

      【讨论】:

        猜你喜欢
        • 2012-10-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-23
        • 2020-06-25
        • 2015-02-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多