c ++ 我的 char* 数组被最后一个添加的元素覆盖
c++ My char* array is getting overwritten by the last element added
您好,我在这个项目上遇到了一些麻烦。假设从文本文件中获取一个句子,然后将其添加到 char* 数组 []。我在 switch 语句中的声明部分遇到问题。当单词长度为 3 个字符时,它会将数组中的所有元素替换为适合的最后一个元素。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int length(const char *a){
int counter=0;
while(a[counter]!= NULL){
counter++;
}
return counter;
}
int main() {
ifstream file;
file.open("C:\Users\casha\Desktop\group_project1\message.txt");
string line;
while(!file.eof()){
getline(file,line);
}
const char* message = line.c_str();
const char *words[9];
words[0]= line.substr(0,4).c_str();
int pos = 0;
int counter = 0;
int wordscounter=0;
while(pos<=length(message)){
if(message[pos]== ' ' || message[pos]== NULL){
switch(counter){
case 3 :
words[wordscounter] = line.substr(pos- counter,counter).c_str();
wordscounter++;
break;
case 4 :
words[wordscounter] = line.substr(pos-counter,counter).c_str();
wordscounter++;
break;
case 5 :
words[wordscounter] = line.substr(pos-counter,counter).c_str();
wordscounter++;
break;
}
counter=0;
pos++;
}
else{
pos++;
counter++;
}
}
for(int x=0;x<=8;x++){
cout << words[x] << endl;
}
应该像这样输出
The
quick
brown
fox
jumps
over
the
lazy
dog
但相反会产生:
dog
jumps
jumps
dog
jumps
lazy
dog
lazy
dog
我读了一些关于未分配内存的内容,我是 c++ 的新手,所以任何帮助都值得赞赏提前感谢!<3
编辑--
如果我像这样手动将值分配给数组
words[3] = line.substr(3,5).c_str();
然后它将打印正确的输出。那么我使用这种方法和我的switch语句有什么区别,这是相同的赋值???
在评论中你写道:
那么我将如何处理分配给
char*
数组而不让字符串悬在语句上。
改变
const char *words[9];
自
std::vector<std::string>> words;
而不是使用
words[0] = line.substr(0,4).c_str();;
用
words.push_back(line.substr(0,4));
在正在使用的其他位置进行类似的更改
words[wordscounter] = line.substr(pos-counter,counter).c_str();
它们可以是:
words.push_back(line.substr(pos-counter,counter));
相关文章:
- lower_bound()返回最后一个元素
- 获取向量C++中第一个值和最后一个值的和
- 获取用C/C++打印的最后一个字符串
- 当我们从/tp地址中添加/减去一个整数时会发生什么
- 使用运算符 [] 引用 std::vector 上最后一个元素时出现问题<>
- 为什么这个程序返回最后一个单词而不是最长的单词?
- 为什么我的最后一个 ELSE 条件无法正确执行
- Lower_bound不适用于具有 3 个元素的向量的最后一个元素
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 仅显示链表的最后一个元素
- 测试迭代器是否位于列表中的最后一个
- push_back通过自行创建的对象获取最后一个元素的向量
- 使用 map.end() 访问 map 的最后一个元素
- 如何知道地图中的最后一个元素是否被删除?
- 如何在 c++ 中将元素添加到数组的最后一个
- c ++ 我的 char* 数组被最后一个添加的元素覆盖
- 链表只打印添加新节点后的最后一个元素
- unique()似乎正在添加最后一个元素的另一个副本
- 将空格字符添加到附加的每个项目,以必须擦除最后一个项目.如何改进
- 如何删除C++中添加到链表中的最后一个元素