c++ - 将类型定义的数组分配给另一个数组 (c++)

标签 c++ arrays

我是编程初学者。我目前的大学作业告诉我从文件中读取文本并且只获取“有效”单词,ie end 而不是 end.。我卡在了必须将检测到的新单词放入单词数组的部分。

编译器错误是:数组必须用大括号括起来的初始化器初始化

int const MAX_WORDS = 100000;
int const MAX_WORDLENGTH = 80;
typedef char Word [MAX_WORDLENGTH];
typedef Word Words [MAX_WORDS];
Words words ;

bool read_file (char filename [80])
{
    ifstream file(filename);
    if(!file) {
        cout << "wrong filename";
        return false;
    }
    char c;
    int word_idx = 0;
    Word word = words[word_idx++];
    int letter_idx = 0;
    int connector_count = 0;
    while (file.get(c)) {
     if ((c>='A' && c<='Z')||(c>='a' && c<='z'))
     {
         word[letter_idx++] = c;
         cout << c << endl;
     }
     else {
        if (c == '-') {
            if(connector_count==0) {
                word[letter_idx++] = c;
                connector_count++;
            }
            else {
                if(connector_count==1) {
                    word[letter_idx-1] ='\n';
                    Word word = words[word_idx++];


                }
            }
        }
     }
    }

最佳答案

这是导致错误的行(您有其中两个):

Word word = words[word_idx++];

通过赋值初始化数组在 C++ 中是非法的,所以例如如果你有这样的东西:

typedef char string[5];
string str = "hello";

然后你尝试做这样的事情:

string str2 = str;

你会得到和你一样的错误。你处理这个的方式是包括

#include <string.h>并这样做:

memcpy(str2, str, sizeof(string));

所以在你的情况下,而不是 Word word = words[word_idx++]; ,你应该这样做:

Word word;  //declare variable
memcpy(word, words[word_idx++], sizeof(Word)); //copy to variable

当然,如果您想避免以后的麻烦,请使用 std::string .

希望这对您有所帮助。

关于c++ - 将类型定义的数组分配给另一个数组 (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19847444/

相关文章:

c++ - AFAIK,下面的代码不应该编译,但它在 clang 和 GCC 中编译。我在这里错过了什么?

python - 使用 Python 导出 4 字节 float

c++ - 类型 'int&' 的引用初始化无效,传递参数 1 时出错

java - foreach 循环中的每个循环?

javascript - 如何使用 Javascript 将 VTT 文件读入数组和循环

c++ - 将参数推送到调用堆栈的可移植方法 (C++)

c++ - 为什么实例化函数模板可以(隐式)使用未声明的符号?

c - 将结构传递给函数并将值存储在结构的元素中

arrays - 如何在swift中对类型化数组进行排序?

java - 如何按日期对数组数组进行排序?