小编Eri*_*sui的帖子

About implicitly convert type 'int' to 'char', why it is different between `s[i] += s[j]` and `s[i] = s[i]+s[j] `

The sample code for demo:

public void ReverseString(char[] s) {
  for(int i = 0, j = s.Length-1; i < j; i++, j--){
        //s[i] = s[i]+s[j]; //<-- error           
        s[i] += s[j];       //<-- ok 

        s[j] = (char)(s[i] - s[j]); //<-- cast
        s[i] -= s[j];
    }
}
Run Code Online (Sandbox Code Playgroud)

As the above code snippet, while s[i] += s[j] is fine without any error. Its equivalent statement s[i] = s[i]+s[j] will cause error as follows

error CS0266: Cannot implicitly convert type 'int' to 'char'. An explicit …

c#

24
推荐指数
1
解决办法
1309
查看次数

是否有必要编写一个"便携式"if(c =='\n')来处理跨平台文件?

这个想法来自关于实际问题的讨论只用一个替换文件中的多个新行.使用在Windows 8.1机器上运行的cygwin终端时发生了错误.

由于行尾终结符不同,比如\n,\r或者\r\n,是否有必要编写"可移植" if(c=='\n')以使其在Linux,Windows和OS X上运行良好?或者,最佳做法是使用命令/工具转换文件?

  #include <stdio.h>
    int main ()
    {
      FILE * pFile;
      int c;
      int n = 0;
      pFile=fopen ("myfile.txt","r");
      if (pFile==NULL) perror ("Error opening file");
      else
      {
        do {
          c = fgetc (pFile);
          if (c == '\n') n++; // will it work fine under different platform?
        } while (c != EOF);
        fclose (pFile);
        printf ("The file contains %d lines.\n",n);
      }
      return 0;
    }
Run Code Online (Sandbox Code Playgroud)

UPDATE1:

CRT会一直将行结尾转换为'\n'吗?

c linux windows macos

6
推荐指数
1
解决办法
329
查看次数

当尝试`uint mask =〜0;`时,常量值'-1'不能转换为'uint'。

演示的示例代码:

public int FindComplement(int num) {
    //uint mask = ~0;       //<-- error CS0031
    //uint mask = (uint)~0; //<-- error

    uint i = 0; 
    uint mask = ~i; //<-- it works

    while((mask&num) != 0) mask <<= 1;

    return (int)~mask^num;
}
Run Code Online (Sandbox Code Playgroud)

当我尝试时uint mask = ~0,它导致如下错误

错误CS0031:常量值“ -1”无法转换为“ uint”

然后,我尝试使用类似的代码uint i = 0; uint mask = ~i来运行它。

我的问题是为什么uint mask = ~0会导致编译错误,还有其他方法可以使它工作吗?

提前致谢

c#

3
推荐指数
1
解决办法
105
查看次数

标签 统计

c# ×2

c ×1

linux ×1

macos ×1

windows ×1