我已经吸取了教训,所以我会简短一点,切入主题。
我需要一个函数,在我的类(class)中,它可以逐行读取文件,并将它们存储到数组/字符串中,以便我可以使用它。
我有下面的例子(请不要笑,我是初学者):
int CMYCLASS::LoadLines(std::string Filename)
{
std::ifstream input(Filename, std::ios::binary | ios::in);
input.seekg(0, ios::end);
char* title[1024];
input.read((char*)title, sizeof(int));
// here what ?? -_-
input.close();
for (int i = 0; i < sizeof(title); i++)
{
printf(" %.2X ";, title[i]);
}
printf("\");
return 0;
}
最佳答案
我不确定你到底在问什么。
但是 - 下面是一些逐行读取文件并将行存储在 vector 中的代码。该代码还打印这些行 - 既作为文本行又作为每个字符的整数值。希望对您有所帮助。
int main()
{
std::string Filename = "somefile.bin";
std::ifstream input(Filename, std::ios::binary | ios::in); // Open the file
std::string line; // Temp variable
std::vector<std::string> lines; // Vector for holding all lines in the file
while (std::getline(input, line)) // Read lines as long as the file is
{
lines.push_back(line); // Save the line in the vector
}
// Now the vector holds all lines from the file
// and you can do what ever you want it
// For instance we can print the lines
// Both as a line and as the hexadecimal value of every character
for(auto s : lines) // For each line in vector
{
cout << s; // Print it
for(auto c : s) // For each character in the line
{
cout << hex // switch to hexadecimal
<< std::setw(2) // print it in two
<< std::setfill('0') // leading zero
<< (unsigned int)c // cast to get the integer value
<< dec // back to decimal
<< " "; // and a space
}
cout << endl; // new line
}
return 0;
}
看你的原码我不笑-没办法-我也曾经是初学者。但是你的代码是 c 风格的代码并且包含很多错误。所以我的建议是:请改用 c++ 风格。例如:永远不要使用 C 风格的字符串(即 char 数组)。太容易出错了...
由于您是初学者(您自己的话:),让我解释一下您的代码:
char* title[1024];
这不是字符串。它是 1024 个指向字符的指针,也可以是 1024 个指向 C 风格字符串的指针。但是 - 您没有保留任何内存来保存字符串。
正确的做法是:
char title[1024][256]; // 1024 lines with a maximum of 256 chars per line
此处必须确保输入文件少于 1024 行,并且每行少于 256 个字符。
这样的代码非常糟糕。输入文件有1025行怎么办?
这就是 C++ 可以帮助您的地方。使用 std::string 你不需要担心字符串的长度。 std::string 容器将根据您放入其中的大小进行调整。
std::vector 就像一个数组。但没有固定尺寸。所以你可以继续添加它,它会自动调整大小。
因此,c++ 提供了 std::string 和 std::vector 来帮助您处理输入文件的动态大小。使用它...
祝你好运。
关于c++ - 逐行读取文件,并将值存储到数组/字符串中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30409547/