C++ C++;将数据从文件读入字符*
我正在尝试从文件中读取行,并将它们保存到char*data[]变量中,代码如下:C++ C++;将数据从文件读入字符*,c++,char,fstream,cout,C++,Char,Fstream,Cout,我正在尝试从文件中读取行,并将它们保存到char*data[]变量中,代码如下: fstream level; level.open("level.txt"); char* row; int i = 0; char* data[3]; while (level >> row) { data[i] = row; cout << i << " " << data[i] << "\n"; i++; } for (i
fstream level;
level.open("level.txt");
char* row;
int i = 0;
char* data[3];
while (level >> row) {
data[i] = row;
cout << i << " " << data[i] << "\n";
i++;
}
for (i = 0; i < 3; i++) {
cout << "\n " << i << " = " << data[i];
}
level.close();
正如您所期望的,第一个cout输出以下内容:
0 aaaaaaaaaaaaaaaaaaaaaaaa
1 aaaaaaaaaaaaaaaaaaaaaaaa
2 aaaaaaaaaaaaaaaaaaaaaaaa
但第二个输出如下:
0 =
1 =
2 =
好像数据[]中的所有数据都已被擦除。有人能告诉我为什么会发生这种情况吗
谢谢您的帮助。既然您使用了标准库(
cout
),为什么不使用string
而不是char*
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
fstream level;
level.open("level.txt");
string row;
int i = 0;
string data[3];
while ((i<3) && (level >> row)) {
data[i] = row;
cout << i << " " << data[i] << "\n";
i++;
}
for (i = 0; i < 3; i++) {
cout << "\n " << i << " = " << data[i];
}
level.close();
#包括
#包括
#包括
使用名称空间std;
流水平;
level.open(“level.txt”);
字符串行;
int i=0;
字符串数据[3];
而((i>行)){
数据[i]=行;
cout既然您使用标准库(cout
),为什么不使用string
而不是char*
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
fstream level;
level.open("level.txt");
string row;
int i = 0;
string data[3];
while ((i<3) && (level >> row)) {
data[i] = row;
cout << i << " " << data[i] << "\n";
i++;
}
for (i = 0; i < 3; i++) {
cout << "\n " << i << " = " << data[i];
}
level.close();
#包括
#包括
#包括
使用名称空间std;
流水平;
level.open(“level.txt”);
字符串行;
int i=0;
字符串数据[3];
而((i>行)){
数据[i]=行;
cout您正在使用指针,而没有为指针分配内存!
您可以自行分配它们,但如果读取的行数超过分配的内存,则必须小心。请尝试此垃圾代码。它使用std向量和字符串,您无需分配内存。您可能需要启用编译器的std-C11开关(std::string::push_back)
fstream级别;
level.open(“level.txt”);
字符行;
int i=0;
std::vector>数据;
data.push_back(std::string());
而(级别>>行){
如果(行!='\n'){
data.back().向后推(行);
cout您正在使用指针,而没有为指针分配内存!
您可以自行分配它们,但如果读取的行数超过分配的内存,则必须小心。请尝试此垃圾代码。它使用std向量和字符串,您无需分配内存。您可能需要启用编译器的std-C11开关(std::string::push_back)
fstream级别;
level.open(“level.txt”);
字符行;
int i=0;
std::vector>数据;
data.push_back(std::string());
而(级别>>行){
如果(行!='\n'){
data.back().向后推(行);
CFUT代码> STD::IfString 不工作。请阅读这里的所有细节:您正在写入未分配的空间+调用UB。考虑使用<代码> STD::String < /C> >,代码> STD::vector < /COD>和<代码> STD::GETLIN()<代码>什么是写入未分配的空间?谢谢,将它改为字符串,而不是char *!可能的复制:<代码>:/fs> <代码>不能这样工作。请阅读这里的所有细节:您正在写入未分配的空间+调用ub。考虑使用<代码> STD::String < /C> >,>代码> STD::vector < /COD>和<代码> STD::GETLIN()
哪个位正在写入未分配的空间?谢谢,将其更改为字符串而不是char*行!可能会重复
fstream level;
level.open("level.txt");
char row;
int i = 0;
std::vector<std::string> > data;
data.push_back(std::string());
while (level >> row) {
if (row!='\n'){
data.back().push_back(row);
cout << row;
else{
data.push_back(std::string());
cout << "\n";
}
for (int i = 0; i < data.size(); i++) {
cout << "\n " << i << " = " << data[i].c_str();
}
level.close();