2012-11-11 92 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; 
} 
相關問題