2013-05-28 152 views
-1

因此,我在使用getline(cin, str);然后string text[str.length()];以及在此之后的语句时想要合并它们(text[e] = text[e] + str[i];),我得到了分段错误。全码:尝试从getline中分配字符时出现分段错误

#include <cstdlib> 
#include <stdio.h> 
#include <iostream> 

using namespace std; 

int main() 
{ 
    string str; 
    int i, e, space = 0; 

    getline(cin, str); 
    string text[str.length()]; 

    for(i=0; i<str.length(); i++) { 
     if(str[i]==' ') { 
      space++; 
      e++; 
     } 
     else { 
      text[e] = text[e] + str[i]; 
     } 
    } 

    return 0; 
} 
+0

变长数组不是标准(还)。 – chris

回答

5

e是未初始化,并且将很可能保持一个随机值超出text界引起段错误的。这不会将所有变量初始化为零:

int i, e, space = 0; 

只有space被初始化为零。更改为:

int i = 0, e = 0, space = 0; 

或:

int i = 0; 
int e = 0; 
int space = 0; 

据我所知,C++不支持可变长度数组。

+0

大声笑,我认为int我,e,空间= 0;将使他们所有的0 :)感谢 – EmiX

+0

'int我,e,空间;''我= e =空间= 0;'会做到这一点。 – user1810087

相关问题