【问题标题】:How to pull out specific data from char array in cpp?如何从cpp中的char数组中提取特定数据?
【发布时间】:2016-01-10 16:53:31
【问题描述】:

我正在做一个学校项目,遇到了一些困难。我的程序读取一个.txt 文件,并一次将它的行分配给 char 数组。

getline(file, line);

char *data = new char[line.length() + 1];

strcpy(data, line.c_str());

// pull out data, convert to int, 
// compare to another variable,
// if true print out the entire line

delete [] data;

所以现在我有一个 char 数组,例如:

"-rw-r--r--  1 jendrek Administ   560 Dec 18  2010 CommonTypes.xsd"
/*note that there are multiple space's in the file*/

我需要做的是我需要从该特定数组中提取文件的大小(例如 560),将其转换为整数并将其与另一个变量进行比较。

这就是我卡住的地方。尝试了我的一些想法,但他们失败了,现在我全力以赴。我将不胜感激每一条建议!

【问题讨论】:

  • 你为什么不直接使用line?我看不出有任何理由复制到data
  • 解析ls 的输出是个坏主意。使用例如stat(或等效的 win32 函数)。
  • @juanchopanza 我认为处理 char 数组会更容易,因为我想访问数组中的某些特定字符。我可能是错的。解析“ls”的输出是该项目的想法,Mat。 ;)
  • 这并不容易。它只会增加内存泄漏的范围,让您更容易越界。
  • 好的,那你推荐什么?我怎样才能访问字符串的内部,让我们说将文件大小值分配给另一个变量以供进一步使用?

标签: c++ arrays char ifstream


【解决方案1】:

由于您使用的是 C++,您可以使用 std::stringstd::vector 执行上述操作,这将为您处理内存管理并拥有 a lot of useful member functions,并编写如下内容:

std::ifstream file(file_name);
// ... desired_length, etc

std::string line;
std::vector<string> text;     

// read the text line by line
while (getline (file, line)) {

    // store line in the vector
    text.push_back(line);
}

// scan the vector line by line
for (size_t i = 0; i < text.size(); ++i) {

    // get length of i-th line
    int line_length = text[i].size();

    // compare length
    if (line_length == desired_length) {

        // print line
        std::cout << text[i] <<'\n';
    }
}

如果要从一行中提取数据并进行比较,可以使用std::stringstream,如下所示:

// initialize a string stream with a line
std::stringstream ss(line);

int variable = 0;

// extract int value from the line 
ss >> variable;    

根据每一行的格式,您可能需要定义一些虚拟变量来提取“无用”数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-27
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多