将iostream输入代码从C++移植到C#

Han*_*ees 4 c# c++ iostream operator-overloading

这是用于读取主存储器地址跟踪的C++代码,用于高速缓存存储器仿真:

 char hex[20];
 ifstream infile;
 infile.open(filename,ios::in);
 if(!infile) {
    cout<<"Error! File not found...";
    exit(0);
 }
 int set, tag, found;
 while(!infile.eof()) { //Reading each address from trace file
      if(base!=10) {
           infile>>hex;
           address = changebase(hex, base);
      } else {
           infile>>address;
      }
      set = (address / block_size) % no_set;
      tag  = address / (block_size * no_set);
 }
Run Code Online (Sandbox Code Playgroud)

我已将其转换为C#代码:

 char[] hex = new char[20];
 FileStream infile=new FileStream(filename, FileMode.Open);

 if (infile == null) {
     Console.Write("Error! File not found...");
     Environment.Exit(0);
 }
 int set;
 int tag;
 int found;
 while (!infile.CanRead) { //Reading each address from trace file
     if (@base != 10) {
         infile >> hex;
         address = changebase(hex, @base);
     } else {
         infile >> address;
     }
     set = (address / block_size) % no_set;
     tag = address / (block_size * no_set);
 }
Run Code Online (Sandbox Code Playgroud)

问题是在线infile >> hex; C#给出了语法错误,因为右移运算符不能应用于字符串运算符.

为什么这不起作用?我正在制作一个小型缓存命中计算项目.

Moo*_*ice 12

量化Eric意味着什么:

C++在可以重载的运算符中非常灵活.它已成为位移操作符提升一个"成语" <<>>也可用于输入和输出.这实际上是有道理的,因为它是一个逻辑构造,眼睛在对象之间注册某种"流".

在C#中,您不会重载这些运算符.Eric意味着,你需要在流对象上明确地说,写(或实际上,读)某些东西.这意味着直接调用方法.

从本质上讲,你正在做同样的事情 - 运算符重载只是一个很好的捷径,但在一天结束时会调用一些方法 - 它是一个很好的装饰"运算符重载"或一个普通的旧函数调用一个名字.

所以,在C++中我们可能会写:

std::cout << "Hello" << std::endl;
Run Code Online (Sandbox Code Playgroud)

而在C#中,我们写道:

Console.WriteLine("Hello");
Run Code Online (Sandbox Code Playgroud)

如果我们忽略std::cout可能与控制台窗口不同的事实(这是说明性的),概念完全相同.

为了扩展运算符的概念,你可能也会遇到诸如stringstream...类似于字符串流的类.这非常有用:

std::stringstream ss;
int age = 25;
ss << "So you must be " << age << " years old.";
Run Code Online (Sandbox Code Playgroud)

在C#中,我们用StringBuilder类实现了这个:

StringBuilder sb = new StringBuilder();
int age = 25;
sb.Append("So you must be ").Append(age).Append(" years old");
Run Code Online (Sandbox Code Playgroud)

他们都做了完全相同的事情.我们也可以这样做:

sb.AppendFormat("So you must be {0} years old", age);
Run Code Online (Sandbox Code Playgroud)

对于更像C的sprintf方法,或者更近期,boost的格式库,这更像是(在我看来).

  • @FredOverflow,"这就是她所说的"?:) (3认同)

Eri*_*ert 9

C#没有使用奇怪的C++约定,即bithifting也意味着流操作.您必须实际调用I/O方法.

  • 或许,你可以通过增加对_which_方法的见解来使答案有用吗?就目前而言,这是一个非常有趣的评论. (3认同)
  • 你写'infile`然后等待Intellisense介入. (3认同)
  • 令人惊讶的是,我被迫对此进行了投票. (2认同)