0

我们的项目是从输入文件中获取二进制数,然后将它们转换为等效的十进制数。我在 jGrasp 中创建了输入文件,因为那是我正在使用的编译器。如果数字之前有一个空格,则忽略它并继续,直到有一个数字。如果数字之间有空格,则会打印出错误消息。除了在我的函数中使用 cin.ignore 之外,我让它工作了一些,现在当我将它更改为 fcin.ignore 时,它​​给了我一条错误消息。我的老师说要改变我的函数以通过引用传递,这样可以解决它,但我不确定我会怎么做。有什么建议么?

//input file
   111101\n
1101\n
11  001\n
111000000000000011101010101010101010100\n


//Program
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;

int main( ){
   // vairables
   char ch;
   int decimal = 0;

   //function prototypes
   void decimalValue (char , int&);



   //declaring filestream
   string fileName;
   ifstream fcin;

   //asking user for file name
   cout << "What is the file called: "<< endl;
   cin >> fileName;

   fcin.open(fileName.c_str());
   fcin.get(ch);
   while (!fcin.eof()){ 

      //fcin.get(ch);
      decimalValue(ch,decimal);
      fcin.get(ch);
    }  // end while
    cout << decimal << endl; 
   fcin.close();

return 0;
}

//functions
void decimalValue( char x, int& y ){
   void improperInput(char , int&);
   if (x == '1'){
      y = ((y *2)+1);
      }
   else if (x == '0'){
      y = (y *2);
      }
   else if (x == '\n'){
      cout << y << endl;
      y = 0;
   }
   else if (x == '2')
      improperInput(x,y);
   else if (x == '3')
      improperInput(x,y);
   else if (x == '4')
      improperInput(x,y);
   else if (x == '5')
      improperInput(x,y);
   else if (x == '6')
      improperInput(x,y);      
   else if (x == '7')
      improperInput(x,y);   
   else if (x == '8')
      improperInput(x,y);
   else if (x == '9')
      improperInput(x,y);
   else if ((y == 0) && (x == ' '))
      fcin.ignore();
   else if ((y != 0) && (x == ' '))
      improperInput(x,y);
}

void improperInput(char x, int& y ){
      fcin.ignore(50,'\n');
      cout << "*Improper Input*" << endl;
      y = 0;

}
4

1 回答 1

0

这看起来很像家庭作业,所以我不会直接回答,而是留下一些东西作为学生的练习。

通过引用传递是您已经在使用int& y. 您还需要了解通过引用传递的内容。

'它打印出错误消息'是什么意思?错误信息是什么?它是什么'?这些是在寻求帮助时能够告诉别人的重要事情。

如果它是编译器错误消息,您应该尝试阅读并理解它的含义。例如,我希望看到类似的错误

error: 'fcin' was not declared in this scope.

请对“范围”的含义以及它如何应用于 c++ 程序中的变量进行适当的研究。

于 2013-10-10T16:01:42.433 回答