2013-03-21 68 views
0

如何從文件中讀取一行字符。首先程序從文件中讀入一個整數。該數字表示在下一步中要讀入多少個字符。接下來讀入字符並將它們存儲在數組中。那麼我該如何創建'char'變量,以便我可以正確讀取Michael中的字符以在數組中顯示它們。使用INPUTFILE >>整數,從那裏我需要一個整數使用,使這個數組字符邁克[整數] ;,然後我可以在讀取字符到數組閱讀字符和創建數組C++

+1

瞭解如何使用'' – 2013-03-21 00:54:45

+0

中的設施這更像是C問題。在C++中,我永遠不會使用原始數組。有花哨的容器和類來容納字符串數組。 – Shoe 2013-03-21 00:55:01

+0

爲什麼不把'Michael'放在文件中並讀取'std :: string'?或者你實際上只是讀取部分字符串/行? – chris 2013-03-21 00:57:40

回答

1

要回答

file.txt: 
8 
Michael 

IM您問題:

#include <fstream> 
using namespace std; 

int main() { 
    ifstream f("file.txt"); 
    int n; 
    f >> n; 
    char chs = new char[n]; 
    for (int i = 0; i < n; ++i) f >> chs[i]; 

    // do something about chs 

    delete [] chs; 
} 

不過,我會去(如果出現在自己的行你Michael):

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

int main() { 
    ifstream f("file.txt"); 
    int n; 
    f >> n; 
    string str; 
    getline(f, str); 
} 
+0

@chris糟糕!謝謝! – gongzhitaao 2013-03-21 00:58:39

+0

即時通訊使用inputFile >>整數,從那裏我需要整數來使這個數組char mike [整數];然後我可以在字符讀入數組 – Mnramos92 2013-03-21 00:58:48

+1

需要檢查「inputFile >>整數」失敗。如果遇到EOF或未找到整數,語句將失敗。 – 2013-03-21 01:31:17

0
#include <fstream.h> 
#include <string.h> 

int main() 


    { 
     ifstream f("file.txt",ios::in); 
     int n; 
     f >> n; 
     char string[n]; 
     f.getline(string,n); 
     cout<<string; 

    } 

這將輸出關閉在file.txt以下字符串。