2012-11-11 47 views
0

我不是要求我寻求帮助的代码。是的,这是一个课程项目。从文件读取并执行按位操作的C++程序

程序读取包含这样的.txt文件,

  • NOT 10100110
  • 和00111101

程序需要根据该操作者读取操作和执行功能改变字节。然后输出更改的字节。

我知道该怎么做:

  • 打开文件了。
  • 从文件中读取。
  • 我可以将字节存储在一个数组中。

我需要什么帮助:

  • 读操作(AND,OR,NOT)
  • 店的每一位内部数组(我可以存储字节而不是位)

我的代码:

#include <iostream> 
#include <fstream> 
#include <istream> 
#include <cctype> 
#include <cstdlib> 
#include <string> 

using namespace std; 

int main() 
{ 
const int SIZE = 8; 
int numbers[SIZE]; // C array? to hold our words we read in 
int bit; 

std::cout << "Read from a file!" << std::endl; 

std::ifstream fin("small.txt"); 


for (int i = 0; (fin >> bit) && (i < SIZE); ++i) 
{            
cout << "The number is: " << bit << endl; 
numbers[i] = bit; 

} 

fin.close(); 
return 0; 
} 
+0

这是什么打印? – alestanis

+0

您正在执行'fin >> bit',其中'bit'未初始化。 – 0x499602D2

+0

@David:是的,是吗? – Beta

回答

0

首先:变化int numbers[SIZE];std::vector<int> numbers(SIZE);。 (#include <vector>

二:我只看到ifstream的是这样的:

std::ifstream ifs; 
ifs.open("small.txt"); 

第三,这就是我的回答:

你忘了阅读操作,请尝试:

#include <string> 
#include <vector> 

int main() 
{ 
using namespace std; // better inside than outside not to cause name clash. 

const int SIZE = 8; 
vector<int> numbers(SIZE); 

ifstream ifs; 
ifs.open("small.txt"); 
if(!ifs.is_open()) 
{  
    cerr<< "Could not open file"<<endl; 
    abort(); 
} 

string operator_name; 
for (int i = 0; !ifs.eof() && (i < SIZE); ++i) 
{            
    ifs >> operator >> bit; 
    cout << "The operator is" << operator_name <<endl; 
    cout << "The number is: " << bit << endl; 
    numbers[i] = bit; 
} 
ifs.close(); // although ifs should manage it by itself, that is what classes are for, aren't they? 
return 0; 
} 
相关问题