2014-09-27 47 views
-2

當我輸入一個超過5個字符的數字時,我正在運行以編碼波紋並獲取訪問衝突錯誤。我不知道代碼有什麼問題,我需要改變什麼?當讀取6位數字時讀取位置錯誤時出現訪問衝突

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

std::string Type(int no) 
{ 
    cout << "this arrives: " << no; 
    return ("this arrives: "+ no); 
} 

int main() 
{ 
    int num; //ID input 
    int i = 0; 
    ifstream reader("TypeID.txt"); //File with ID names 

    if (!reader) { 
     cout << "Error opening input file" << endl; //Display error 
    } 
    else { 
     cout << "input TypeID number" << endl; //When sucsesful display user instructions 
     while (true) //while the file has loaded run Type conversion 
     { 
      cout << "TypeId: "; //Prompt user to enter Type no 
      cin >> num; //put input into int "num" 

      while (num > 0) { //num greater than 0 
       Type(num); 
       cout << endl; 
       break; 
      } //as long as input is greater than 0 Type functio is run and Type name is returned 
      cout << endl << "Next number for conversion" << endl; 
     } 
     return 2; 
    }; 
} 

如果你運行該代碼只使用一個虛擬文件的文件TypeID.text它正在尋找的代碼將無法查找的內容呢。

+0

什麼行會導致錯誤? – 2014-09-27 15:35:56

+0

當它運行並輸入一個6位數字後,它會中斷。源代碼沒有錯誤。 – user3797758 2014-09-27 15:37:43

+0

源代碼確實有錯誤,否則會起作用。我問的是,什麼行導致崩潰? (提示:在調試器中運行它。) – 2014-09-27 15:38:20

回答

0

這個表達式,

("this arrives: "+ no); 

是指針運算。指向文字第一個字符的指針被移動no內存中的位置數。在外部環境中,所得到的指針用於構造std::string,其使用具有未定義的行爲如果no大於14左右。

爲了什麼你可能打算,做

"this arrives: "+ to_string(no); 

還有很多其他可能被固定和/或改善,但與上面開始。


爲了避免<stdafx.h>關閉使用預編譯頭在你的Visual Studio項目設置。

+0

我知道有很多要添加的,我想這是更多我改變了返回值爲: return(「main」); 因爲我不需要返回數字,所以它沒有任何問題 – user3797758 2014-09-30 18:05:13

相關問題