为什么 getline() 在我的代码 (c++) 中不起作用
Why is getline() not working in my code (c++)?
我有类"消息",其中包括成员:
protected:
int * next;
int amount;
std::string ** mes;
public:
message(std::ifstream*);
构造函数的代码是:
message :: message(ifstream * myfile){
*myfile >> amount;
if (amount==0){
next = new int[1];
*myfile >> next[0];
mes = new string*[1];
getline(*myfile,*mes[0]);
}
else{
next = new int[amount];
mes = new string*[amount];
for (int i=0;i<amount;i++){
*myfile >> next[i];
getline(*myfile,*mes[i]);
}
}
}
使用运算符>>从文件中读取工作正常,但是程序在getline()上崩溃 - 为什么?我应该更改什么?
您没有为要求std::getline()
读取的std::string
变量分配任何内存。 您正在分配不指向任何内容的string*
指针数组。 您需要将代码更改为:
-
继续使用指针数组,但为它们分配实际的
string
变量:std::string ** mes;
if (amount == 0) { ... mes = new string*[1]; mes[0] = new string; // <-- here std::getline(*myfile, *mes[0]); } else { ... mes = new string*[amount]; for (int i = 0; i < amount; ++i) { mes = new string[amount]; // <-- here } for (int i = 0; i < amount; ++i) { ... std::getline(*myfile, *mes[i]); } }
-
首先删除不必要的间接级别:
std::string * mes;
if (amount == 0) { ... mes = new string[1]; std::getline(*myfile, mes[0]); } else{ ... mes = new string[amount]; for (int i = 0; i < amount; ++i) { ... std::getline(*myfile, mes[i]); } }
也就是说,您应该停止使用原始数组,而是使用 std::vector
:
#include <vector>
protected:
std::vector<int> next;
std::vector<std::string> mes;
int amount;
message :: message(ifstream * myfile) {
*myfile >> amount;
if (amount == 0) {
next.resize(1);
mes.resize(1);
*myfile >> next[0];
std::getline(*myfile, mes[0]);
}
else {
next.resize(amount);
mes.resize(amount);
for (int i = 0; i < amount; ++i) {
*myfile >> next[i];
std::getline(*myfile, mes[i]);
}
}
}
无论哪种方式,您都应该考虑摆脱amount == 0
情况下的冗余代码。 使用局部变量,如果amount
为 0,则将其设置为 1,否则将其设置为实际amount
,然后您可以使用单个代码行来执行分配,而不考虑amount
值:
message :: message(ifstream * myfile) {
*myfile >> amount;
int numElements = (amount == 0) ? 1 : amount;
next = new int[numElements];
mes = new string[numElements];
for (int i = 0; i < numElements; ++i) {
*myfile >> next[i];
getline(*myfile, mes[i]);
}
}
message :: message(ifstream * myfile) {
*myfile >> amount;
int numElements = (amount == 0) ? 1 : amount;
next.reserve(numElements);
mes.reserve(numElements);
for (int i = 0; i < numElements; ++i) {
int value;
*myfile >> value;
next.push_back(value);
std::string line;
std::getline(*myfile, line);
mes.push_back(line);
}
}
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++为什么尽管我调用了void函数,它却不起作用
- 为什么在保护模式下继承升级不起作用
- 循环在计数器中不起作用
- 在其他文件中创建类时在 c++ 项目中不起作用
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 为什么二进制搜索在我的测试中不起作用
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 带有指定长度字符* 参数的 std::regex_search 在 VS2017 中不起作用?
- Bjarne Stroustrup Book - std_lib_facilities.h - 不起作用(未知类型名称)
- 为什么简单的算术减法在"if"条件下不起作用?
- 为什么Stroustup书中的has_f不起作用
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 嵌套While循环不起作用(C++问题)
- C++Matching Brackets 2解决方案不起作用
- 为什么这段代码不起作用,我该如何解决?
- 我正在开发服务器,ip作为参数传递不起作用