C ++字符串长度错误异常

时间:2014-04-13 07:57:30

标签: c++ string runtime-error

我有一个我正在阅读的文本文件,其中包含以下内容:

file "transform.in" .....:
10
@--------@
----------
----------
----------
----------
----------
----------
----------
----------
----------
@---------
----------
----------
----------
----------
----------
----------
----------
----------
---------@
(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 个答案:

答案 0 :(得分:2)

C ++中的字符串始终以NULL字符终止,写为'\0'。由于输入文件每行包含10个字符,因此您可以尝试这样的操作:

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