gpt4 book ai didi

c++ - 简单的从文本文件中读取算法不起作用

转载 作者:行者123 更新时间:2023-11-28 03:11:12 24 4
gpt4 key购买 nike

我有一个包含如下键和值的文本文件:

keyOne=1
keyTwo=734
keyThree=22.3
keyFour=5

键只是像我的示例中的小写和大写字母。这些值是整数或 float 。每个键和值由等号 (=) 分隔。现在我想将这些值读入我程序中的变量。

这是我试图读取值的代码:(我省略了将值存储在程序变量中的部分,现在将它们打印出来以进行演示。)

std::fstream file(optionsFile, std::fstream::in);

if (file.good()) {
int begin;
int end;
std::string line;

while(std::getline(file, line)) {

// find the position of the value in the line
for (unsigned int i = 0; i < line.length(); i++) {
if (line.at(i) == '=') {
begin = i + 1;
end = line.length();
break;
}
}

// build the string... it starts at <begin> and ends at <end>
const char *string = "";
for (int i = begin; i < end; i++) {
string += line.at(i);
}

// only gibberish is printed in the following line :(
std::cout << "string=" << string << std::endl;
}
}

我不明白为什么它不打印值.. 而是只打印奇怪的东西甚至什么都不打印

请帮帮我,这让我精神崩溃了:(

最佳答案

您正在使用没有正确分配内存的 C 风格字符串(字符数组),并且您只是在使用指针进行操作,因此您没有将字符附加到字符串中:

   // build the string... it starts at <begin> and ends at <end>
const char *string = "";
for (int i = begin; i < end; i++) {
string += line.at(i);
}

改用std::string:

/// build the string... it starts at <begin> and ends at <end>
std::string str;
for (int i = begin; i < end; i++) {
str += line.at(i);
}

或者手动分配内存,使用适当的索引,以 '\0' 字符终止字符串,不要忘记删除不再需要的字符串:

char *string = new char[end - begin + 1];
int j = 0;
for (int i = begin; i < end; i++) {
string[j++] = line.at(i);
}

// Don't forget to end the string!
string[j] = '\0';

// Don't forget to delete string afterwards!
delete [] string;

因此,只需使用 std::string

编辑 为什么首先混合使用 C 字符串和 std::string

关于c++ - 简单的从文本文件中读取算法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18420281/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com