2015-11-02 100 views
1

Tab键分隔example.txt文件:值不能用于初始化类型为“字符”的实体

1 MODEL1 
2 MODEL2 
3 MODEL3 

我的主:

int main() 
{ 
    int number; 
    char model[6]; 
    list myList; 

    ifstream infile; 
    infile.open("example.txt"); 

    //reading first line from file 
    infile >> (int)number; 
    infile >> model; 
    myList.Insert({ number, model}, 1); // error here on model 

    return 0; 
} 

myList中类的伪:

struct data{ 
    int number; 
    char model[6]; 
}; 

struct Node{ 
    data data; 
    ... 
}; 

Node = myNode[100] 

void Insert(data x, int position) 
{ 
    myNode[position].data = x; 
} 

我从example.txt文件读取我的第二行字符有问题。如何将MODEL1,MODEL2,MODEL3读入myList?

+0

除了编译错误,您还有一个缓冲区溢出错误。从流中读取字符串时,会附加空终止符字符。您的型号名称包含6个字符。因此,当流入7个字符时,你会溢出'char model [6]'。 – user2079303

+0

与你的问题无关,但你有一个更严重的错误,即*缓冲区溢出*。你声明一个由6个字符组成的数组,但是你会在数组中写入* 7个*字符,写出越界并导致*未定义的行为*。你忘记了C风格的字符串需要额外的字符来终止字符串。改用['std :: string'](http://en.cppreference.com/w/cpp/string/basic_string)。顺便说一句,使用'std :: string'将解决你所问的问题。 –

+1

在'main'中,为什么不声明'struct data data_item;'并且读'infile >> data_item.number;'和'infile >> data_item',而不是分别声明'int number'和'char model [6]'。模型“,然后调用'myList.Insert(data_item,1);'? – lurker

回答

1

{number, model}正尝试初始化成员变量model作为本地model的副本,但原始数组无法被复制初始化。

你将不得不使用std::string

int main() 
{ 
    int number; 
    std::string model; 
    list myList; 

    ifstream infile; 
    infile.open("example.txt"); 

    infile >> number; 
    infile >> model; 
    myList.Insert({number, model}, 1); 
} 

struct data 
{ 
    int number; 
    std::string model; 
}; 

这也将修复的缓冲区溢出错误,@ user2079303和@JoachimPileborg发现。


可以也保持原阵列,并手动strncpy当地model数组成员model。然而这在C++中并不建议。

+0

行infile >>模型给出错误:没有opperator“>>”匹配这些操作数操作数类型是:std :: ifstream >> std :: string; – Dancia

+0

你有没有'#include '? – emlai

+0

现在正常工作,谢谢。认为我不需要任何其他包括,因为它已经std :: – Dancia