逐行读取文件,并将值存储到数组/字符串中
Read file, line by line, and store values into a array/string?
我已经得到了教训,所以我将长话短说。
我需要一个函数,在我的类中,可以逐行读取文件,并将它们存储到数组/字符串中,以便我可以使用它。
我有下面的例子(请不要笑,我是一个乞丐):
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风格的代码,包含很多bug。所以我的建议是:请使用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来帮助你处理输入文件的动态大小。使用它…好运。
相关文章:
- 使用 jsoncpp 解析 json 数组字符串
- C++ 对象数组字符串输入在控制台上不起作用
- 插入了 C++ 数组字符串数据,但在显示输出时不显示
- 无法区分 JSON 对象/数组/字符串
- 为什么数组(字符串类型)的大小是 24 字节,带有单个空格元素
- 如何使用数组字符串进行输入验证
- (C++) 打印字符数组字符串的单词时出现问题
- 使用Back_inserter从任何位置的输入字符中使用Back_inserter进行过滤数组字符串
- C 函数反转字符数组字符串
- 如何在 c++ 中创建数组(字符串 [] )的向量
- 如何返回数组字符串的指针
- char数组字符串混淆
- 如何从字符数组字符串中提取空格
- 是否可以将 Bitset<8> 的值复制到数组字符串而不转换它们?
- C++数组字符串函数
- 如何在函数中操作字符数组(字符串)的指针,该指针在C / C ++中作为参数传递
- visual将音频文件存储到数组/字符串流C++中
- c++在char数组(字符串)上将what替换为
- 将数组字符串转换为intger c++(初学者)
- 需要设置数组字符串长度,使其恰好为13