2014-10-17 31 views
0

所以我有一個項目(我不希望任何人爲我做我的硬件,但我現在在第一個3個數據結構上剛剛結束所以我可以開始我的項目),我需要通過運行一些文件來填充幾個地圖,我的示例文件被設置在我需要提取long的值作爲將作爲地圖中的字符串的值的鍵,像這樣:通過一個文件來填充地圖和分割空白空間

0 A 

1 B 

2 C 

凡我對顯然是0是關鍵,這將是該項目的一個字符串,問題是,我的教練也說,這將是一個可能的格式:

0 W e b 1 

1 W e b 2 

2 W e b 3 

其中0是「W e b 1」的關鍵。我知道我需要在空格上劃分,但是說實話,我甚至不知道從哪裏開始,我嘗試了幾個方法,但是在第二種情況下,我只能得到字符串的第一個字符。

這裏最終是我所坐的,不用擔心整個布爾返回和事實,我知道整個打開文件,並檢查它應該發生在這個函數之外,但我的教授想要所有在這個功能。

bool read_index(map<long, string> &index_map, string file_name) 
{ 
    //create a file stream for the file to be read 
    ifstream index_file(file_name); 

    //if file doesn't open then return false 
    if(!index_file) 
     return false; 

    string line; 
    long n; 
    string token; 
    //read file 
    while(!index_file.eof()) 
    { 
     getline(?) 
     //not sure how to handle the return from getline 
    } 

    //file read? 
    return !index_file.fail(); 
} 
+1

馬上就掉,['while(!index_file.eof())''是錯的](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong)。使用'while(std :: getline(index_file,line))'並在循環體中丟失'getline'。 *始終*檢查您的IO操作是否成功;從不認爲他們沒有失敗。 – WhozCraig 2014-10-17 21:40:01

回答

0

你可能使用的strtok()用於線路分裂,如果你是一個純C的情人,但有一個分裂的文件數據的好舊的C++方法就是:CIN流重定向到文件,它拆分任何有效的分隔符 - 空格,製表符,換行符,你只需要爲自己保留一個行計數器

std::ifstream in(file_name); 
std::streambuf *cinbuf = std::cin.rdbuf(); //better save old buf, if needed later 
std::cin.rdbuf(in.rdbuf()); //redirect std::cin to file_name 

// <something> 

std::string line; 
while(std::getline(std::cin, line)) //now the input is from the file 
{ 
    // do whatever you need with line here, 
    // just find a way to distinguish key from value 
    // or some other logic 
}