2014-04-13 82 views
-2

我有我從閱讀幷包含以下內容的文本文件:C++字符串長度錯誤異常

file "transform.in" .....: 
10 
@[email protected] 
---------- 
---------- 
---------- 
---------- 
---------- 
---------- 
---------- 
---------- 
---------- 
@--------- 
---------- 
---------- 
---------- 
---------- 
---------- 
---------- 
---------- 
---------- 
[email protected] 
(end of file) 

,我使用下面的代碼創建一個segmation故障:

#include <fstream> 
    #include <iostream> 
    #include <string> 

    using namespace std; 

    ifstream input("transform.in"); 
    ofstream output("transform.out"); 
    int n; 
    char arxiko[10][10] = {0}; 
    string teliko = "", line; 

    int main() 
    { 
     input >> n; 
     for (int i=0; i<n; i++) 
      input >> arxiko[i]; 
     for (int i=0; i<n; i++) 
    { 
     input >> line; 
     teliko += line; // here, in the first iteration the segmation fault occurs 
    } 

如果一行包含9個字符而不是10個,沒有問題,但是有10個崩潰! 此外,我做了一些與字符串+ =運算符的測試,我可以追加一個大於10個字符的字符串成功,但爲什麼我在這失敗?

+1

10個字符(終止爲0)會生成11個字節。 –

+0

你爲什麼要一起使用'char **'以及'std :: string'? – CinCout

+0

@gargankit,因爲這是產生錯誤的代碼段。在剩下的程序中,我需要char ** - 字符串有兩個索引值(arxiko [i] [j])。 – manolismi

回答

2

C++中的字符串始終以NULL字符結尾,寫爲'\0'。由於輸入文件每行包含10個字符,因此您可以嘗試如下所示:

char arxiko[11][11] = {'\0'}; 
+1

問題表面不一定在何處產生的地方。您可以使用標準庫類和手寫內存管理與原始數組;問題顯然是後者。 –