如何从cpp中的char数组中提取特定数据?
How to pull out specific data from char array in cpp?
我正在做一个学校项目,遇到了一些困难。我的程序读取一个 .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;
所以现在我得到了一个字符数组,例如:
"-rw-r--r-- 1 jendrek Administ 560 Dec 18 2010 CommonTypes.xsd"
/*note that there are multiple space's in the file*/
我需要做的是从该特定数组中提取文件的大小(例如 560),将其转换为整数并将其与另一个变量进行比较。
这就是我卡住的地方。尝试了我的一些想法,但他们失败了,现在我全力以赴。我将不胜感激每一条建议!
由于您使用的是 C++,您可以使用 std::string
和 std::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;
根据每一行的格式,您可能需要定义一些虚拟变量来提取 "useless" 数据。
我正在做一个学校项目,遇到了一些困难。我的程序读取一个 .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;
所以现在我得到了一个字符数组,例如:
"-rw-r--r-- 1 jendrek Administ 560 Dec 18 2010 CommonTypes.xsd"
/*note that there are multiple space's in the file*/
我需要做的是从该特定数组中提取文件的大小(例如 560),将其转换为整数并将其与另一个变量进行比较。
这就是我卡住的地方。尝试了我的一些想法,但他们失败了,现在我全力以赴。我将不胜感激每一条建议!
由于您使用的是 C++,您可以使用 std::string
和 std::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;
根据每一行的格式,您可能需要定义一些虚拟变量来提取 "useless" 数据。