非 POD 元素类型 'string'(又名 '<char>basic_string')c++ 的可变长度数组
Variable length array of non-POD element type 'string' (aka 'basic_string<char>') c++
我在非POD元素类型string
(又名basic_string<char>
)的c++代码可变长度数组中收到此错误。
string words[numWords];
如果我去掉numWords并输入一个数字,这很好,但如果我把同一个数字放在一个变量中,就会出现Variable length array of non-POD element type 'string' (aka 'basic_string<char>')
错误,我以前也这样做过,它在visualstudio中有效,但我现在在Xcode中尝试过,但它不起作用。我试过使用矢量,但我无法获得它们来存储任何数据,它们只是返回空白。
对于那些问这是我的矢量代码应该都在那里
char ch;
ifstream repFile("//Users//bobthemac//Documents//c++asignment//c++asignment//test1.txt");
while(repFile.get(ch))
{
if(ch == ' ' || ch == 'n' || ch == 't')
{
numWords++;
}
}
vector<string> words (numWords);
while(repFile >> x)
words.push_back(x);
repFile.close();
C++没有C99风格的可变长度数组。您的编译器可能支持它们作为扩展,但它们不是语言的一部分。在这种特定的情况下,您在VisualStudio中的成功表明它实际上具有这样的扩展。clang++将支持VLA,但仅支持POD类型,因此您尝试创建string
对象的VLA是行不通的。如果我省略了足够多的警告/错误标志,g++在我的机器上确实有效。
这用numWords
空字符串初始化words
,然后附加实际字符串:
vector<string> words (numWords);
while(repFile >> x)
words.push_back(x);
更改为:
vector<string> words;
while(repFile >> x)
words.push_back(x);
或:
vector<string> words (numWords);
int idx = 0;
while(repFile >> x /* && idx < numWords */)
words[idx++] = x;
编辑:
在填充vector
:之前,没有理由计算字数
vector<string> words;
ifstream repFile("//Users//bobthemac//Documents//c++asignment//c++asignment//test1.txt");
if (repFile.is_open())
{
while(repFile >> x)
{
words.push_back(x);
}
repFile.close();
}
对不起,您需要编写gcc --version
才能获得版本。
正如其他人所说,不应该使用可变长度数组,但GCC确实支持将它们作为C++中的扩展。我的GCC 4.4.4用以下代码编译得很好:
#include <string>
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
string s[n];
return 0;
}
那个代码是为你编译的吗?如果是这样,那么您需要给我们一段最小的失败代码。
不过,最好的解决方案是使用vector<string>
。
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- std中有类似find_last_of的函数,而string中没有
- 使用 std::string () const 函数启动线程或未来
- 使用char类型将decimal转换为string,将string转换为decimal
- 迭代和比较映射<字符串、矢量<string>> c++ 中的值
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 将向量解析<string>为字符串
- 'string.assign(string.data(), 5)' 是明确定义的还是 UB?
- 如何更改大小(std::string)
- "string.h"在构建适用于iOS的qt应用程序中找不到消息
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- std::string 的对象真的可以移动吗?
- 与'operator='不匹配(操作数类型'String'且"void")
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- <string> 使用 for 循环写入向量
- 确切地说,如何解释 std::getline(stream, string) 函数在C++中填充的字符串