2016-09-21 15 views
-2

我目前正在實現一個基本的文件加載函數。當使用std::stringstream時,該程序在stringstream析構函數中發生訪問衝突時崩潰。下面是函數:在windows上使用std :: stringstream時的訪問衝突

void macro_storage_t::load(std::string filename) 
{ 
    std::ifstream file(filename); 
    if (file.is_open()) 
    { 
     clear(); 

     char line_c[4096]; 
     while (file.getline(line_c, 4096)) 
     {  

      std::string line(line_c); 
      if (line.find("VERSION") == std::string::npos) 
      { 
       std::stringstream ss(std::stringstream::in | std::stringstream::out); 
       int a, b, c, d; 

       ss << line; 
       ss >> a >> b >> c >> d; 
       entry_t entry; 
       entry.timestamp = a; 
       entry.type = static_cast<entry_type_t>(b); 
       entry.button = static_cast<button_t>(c); 
       entry.key = static_cast<BYTE>(d); 

      } 
     } 
    } 
} 

它加載的文件看起來像這樣(縮短了更好的可讀性):

VERSION 1 
0 14 254 0 

,並保存有這樣的功能:

void macro_storage_t::save(std::string filename) 
{ 
    std::ofstream file(filename, std::ios::trunc); 
    if (file.is_open()) 
    { 
     file << "VERSION " << MACRO_VERSION << std::endl; 
     for (std::vector<entry_t>::iterator it = entry_list_.begin(); it != entry_list_.end(); ++it) 
     { 
      entry_t entry = *it; 
      file << (int)entry.timestamp << " " << (int)entry.type << " " << (int)entry.button << " " << (int)entry.key << std::endl; 
     } 
     file.close(); 
    } 
} 

的錯誤是:

Unhandled exception at 0x0f99a9ee (msvcp100d.dll) in FLAP.exe: 0xC0000005: Access violation reading location 0x00000004. 

錯誤一旦被stringstream隱含刪除後會出現...

我使用Visual Studio 2010在Windows 7

+0

你爲什麼不讀入'線'直接跳過line_c,'std :: getline(std :: cin,line)'? – kfsone

+0

在調試器中運行它會發生什麼? – kfsone

+2

_「我現在正在調試這個問題15分鐘......」_我不確定這是否有效在Stack Overflow中提出問題。通常你會在你來這裏之前花更多的精力。 –

回答

0

試試這個:

void macro_storage_t::load(std::string filename) 
{ 
    std::ifstream file(filename); 
    if (file.is_open()) 
    { 
     clear(); 

     std::string line; 
     if (std::getline(file, line)) 
     {  
      if (line.substr(0, 8) == "VERSION ") 
      { 
       // optional: read the actual version number from the line, 
       // if it affects how the following values must be read... 

       while (std::getline(file, line)) 
       { 
        std::istringstream ss(line); 
        int a, b, c, d; 

        if (ss >> a >> b >> c >> d) 
        { 
         entry_t entry; 

         entry.timestamp = a; 
         entry.type = static_cast<entry_type_t>(b); 
         entry.button = static_cast<button_t>(c); 
         entry.key = static_cast<BYTE>(d); 

         entry_list_.push_back(entry); 
        } 
       } 
      } 
     } 
    } 
} 
+0

同樣的問題... – Nidhoegger

+0

然後,你可能要麼有一個不好的安裝,或者編譯器正在生成糟糕的codegen。 –

+0

你知道我能做些什麼嗎? – Nidhoegger