c ++ 我的 char* 数组被最后一个添加的元素覆盖



您好,我在这个项目上遇到了一些麻烦。假设从文本文件中获取一个句子,然后将其添加到 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));

最新更新