2012-02-25 22 views
0

這是我的問題:我從txt讀取一些行。這個TXT是這樣的:我的字符串從ifstream也獲得「 n」

Ciao: 2000 
Kulo: 5000 
Aereo: 7000 

ecc。我必須將(':')之前的每個單詞分配給一個字符串,然後分配給一個地圖;並將數字轉換爲int,然後轉換爲地圖。問題是從第二行開始,我的字符串變成(「\ nKulo」)ecc!我不想要這個!我能做什麼?

這是代碼:

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

     int main() 
     { 
      map <string, int> record; 
      string nome, input; 
      int valore; 
      ifstream file("punteggi.txt"); 

      while (file.good()) { 
       getline(file, nome, ':'); 
     //  nome.erase(0,2); //Elimina lo spazio iniziale 
       file >> valore; 
       record[nome] = valore; 
       cout << nome; 
      } 
      file.close(); 

      cout << "\nNome: "; 
      cin >> input; 
      cout << input << ": " << record[input] << "\n"; 

      cout << "\n\n"; 
      return 0; 
     } 
+0

不相關,但使用'std :: endl'而不是'「\ n」'。 – 2012-02-25 15:36:18

+0

你可以使用'std :: string :: substr'跳過第一個字符。 – 2012-02-25 15:37:49

+0

@ J.N。 - 使用'std :: endl'和'\ n' - 'std :: endl'會導致緩衝區刷新。 – birryree 2012-02-25 15:38:23

回答

2

您遇到的問題是std::getline()是一個未格式化的輸入函數,因此不會跳過前導空格。從外觀上來看,你要跳過前導空白:

while (std::getline(in >> std::ws, nome, ':') >> valore) { 
    ... 
} 

或者,如果有前導空格,你可以ignore()所有字符,直到達到行的末尾讀值之後。

順便說一句,因爲我看到有人在這裏推薦使用的std::endl使用std::endl,除非你真的打算刷新緩衝區。編寫文件時,這是一個常見的主要性能問題。

1

使用標準線讀成語:

for (std::string line; std::getline(file, line);) 
{ 
    std::string key; 
    int n; 
    std::istringstream iss(line); 

    if (!(iss >> key >> n) || key.back() != ':') { /* format error */ } 

    m.insert(std::make_pair(std::string(key.cbegin(), std::prev(key.cend()), 
          n)); 
} 

(取而代之的是臨時​​字符串從 - 迭代器,你也可以使用key.substr(0, key.length() - 1),雖然我想象我的版本可能會更有效一些,或者在將數據插入地圖之前添加一個key.pop_back();)。

+0

糾正我,如果我錯了。爲什麼不'm.insert(std :: make_pair(key,n))'?我們沒有在'if'條件語句中提取它們嗎? – Mahesh 2012-02-25 15:50:21

+0

@Mahesh:我以爲你可能想脫掉冒號!我想你也可以在單獨的語句中說'key.pop_back()'。條件只是確保最後一個字符確實是一個冒號。 – 2012-02-25 15:56:50