2011-09-22 165 views
1

在我的計劃,我輸入一個文件,並在文件中是這樣的:I/O C++從文本文件閱讀

11267 2 500.00 2.00

...那是一條線。有相同的順序設置更多的行。我需要將第一個號碼11267輸入到actnum。在那之後,2轉換爲choice等等。我簡單地沒有找出如何將第一個5位數字輸入到第一個變量的邏輯。

actnum = 11267; 
choice = 2; 

編輯*

我都認爲:

#include <fstream> 
#include <iostream> 
using namespace std; 



void main() 
{ 
    int trans = 0, account; 
    float ammount, bal; 

    cout << "ATM" << endl; 

等等等等

我只是不知道如何得到它只有輸入具體的數字了進去。就像我在做「actnum」選擇時一樣,它是如何知道只把前5個數字放在裏面的?

回答

1

fscanf是你在找什麼。它與scanf相同,但是用於文件。

unsigned int actnum, choice; 
float float1, float2; 

FILE *pInputFile = fopen("input.txt", "r"); 

fscanf(pInputFile, "%u %u %f %f", &actnum, &choice, &float1, &float2); 
+0

雖然這是用C stdio庫,而不是C++的fstream的,我找到了簡潔的格式字符串更具可讀性。特別是格式更復雜。 – nimrodm

+0

不要忘了在程序開始時'#include ',否則這個程序不會編譯 –

+1

如果你要這樣做,最好'#include '而不是。它應該更好地用C++ –

1
input_file_stream >> actnum >> choice >> ... 
+2

+ +1來實現它。只是一個建議:要清楚的是'input_file_stream'是'的std :: ifstream'和OP指向文檔 –

+0

我都認爲: 的#include 的#include 使用命名空間std; void main() { \t int trans = 0,account; \t float ammount,bal; \t cout <<「ATM」<< endl; etc etc 我只是不知道如何讓它只輸入到它的具體數字。就像我在做「actnum」選擇時一樣,它是如何知道只把前5個數字放在裏面的? – Brisil

+0

這些是5位數字,但是是單個數字。當你提取一個整數時,它讀取它可以解釋一個整數,而空格標記它的結束。 –

2

使用C++ <fstream>庫。 fscanf()是略顯過時,你可能會從<fstream>獲得更好的性能,更何況該代碼是一個更容易閱讀:

#include <fstream> 
using namespace std; 

ifstream fileInput("C:\foo.txt"); 
fileInput >> actnum >> choice >> float1 >> float2; 
+2

+1快速,刪除「*,你可能會從'' *」獲得更好的性能,然後進行一些微型優化,這是一個邪惡的傢伙出現並無緣無故地降低了你的評價。 –

+0

@muntoo笑,如果它運行得更快,他們應該是幸福的:)另外,即使不運行速度更快,可讀性是顯著獎金(特別是C++) –

+0

我都認爲: 的#include #包括 using namespace std; void main() { \t int trans = 0,account; \t float ammount,bal; \t cout <<「ATM」<< endl; etc etc 我只是不知道如何讓它只輸入到它的具體數字。就像我在做「actnum」選擇時一樣,它是如何知道只把前5個數字放在裏面的? – Brisil