2016-02-13 97 views
-4

我正在尝试做一个简单的人口统计输入 - >输出程序。输入个人信息并将其写入csv文件。但是我无法获得名称部分的工作。我总是遇到分段错误。下面的代码是有问题的位,并且不起作用。我知道它与字符串有关,如果我更改为int,它工作得很好。所有其他数据输入(为简单起见,已被删除)的作品。C++传递字符串导致分段错误

主要

#include <iostream> 
#include "People.h" 
using namespace std; 
void demographics(); 

int main() 
{ 
    demographics(); 
    return 0; 
} 

void demographics() 
{ 
    short elements = 2; 
    Names test[elements]; 
    vector<string> name2; 
    for(int i =0; i<=elements; i++) 
    { 
     string name; 
     cout << "Please enter first name for child " << i+1 << endl; 
     cin >> name; 
     name2.push_back(name); 
     test[i].setName(name2); 
    } 
    return; 
} 

People.h

#ifndef PEOPLE_H_INCLUDED 
#define PEOPLE_H_INCLUDED 
#include <iostream> 
#include <string> 
#include <vector> 

using namespace std; 

class Names 
{ 

    private: 
     vector<string> names; 
    public: 
     void setName(vector<string>&); 
}; 

People.cpp

#include "People.h" 
#include <iostream> 

using namespace std; 

void Names::setName(vector<string>& f_l_name) 
{ 
    names = f_l_name; 
} 
+0

这就是我正在寻找的3个元素。我想输入3人的信息。为什么会导致错误?为了澄清我确实改变为<,它的工作原理 – NoiseyAgent

+0

'名称测试[2];'创建一个包含两个元素而不是三个元素的数组。之后使用'test [1]'得到第二个元素,因为索引从0开始...初始化不是索引。 – LogicStuff

回答

7

for(int i =0; i<=elements; i++)

应该是

for(int i =0; i < elements; i++)

+0

你是说for循环不应该结束吗?它应该只读(int i = 0; i)? – NoiseyAgent

+0

@ user3547452:pdm在说你阅读的内容太多了。 –

+0

好吧,这是有道理的,当它第一次发布它只是说(INT 1 = 0;我 – NoiseyAgent