已编辑 我如何将其拆分为 char 和 int 数组

EDITED How do I split it up into char and int arrays

本文关键字:char int 数组 拆分 编辑      更新时间:2023-10-16

我不知道帖子发生了什么,但它一定发生在我的第一次编辑中。

当这些信息在单独的文件中时,我得到了这些信息进入并工作。 但是我需要它在一个文件中。
我查看了我的教科书和一堆其他地方,但我找不到如何只从文件中取出文本或字符。 我已经将所有信息放入一个数组中,但看起来我需要逐个拉出每个组并将其放在我想要的位置,但这看起来很慢、乏味且非常容易出错。

Johnson 85 83 77 91 76 
Aniston 80 90 95 93 48 
Cooper 78 81 11 90 73  
Gupta 92 83 30 69 87   
Blair 23 45 96 38 59  
Clark 60 85 45 39 67   
Kennedy 77 31 52 74 83
Bronson 93 94 89 77 97 
Sunny 79 85 28 93 82  
Smith 85 72 49 75 63

如果这看起来很熟悉,它与我之前的帖子是相同的任务,现在我只需要弄清楚如何解析这些信息并再次使用它。

很有可能,您需要将输入的值作为字符串值并检查它以找到数字字符的开头。

只有在将输入字符串的字母部分与其数字部分分开后,您才开始创建目标数组。

这可能会有所帮助:如何有效地检查字符串是否在C++中包含特殊字符?

/e:措辞

有多种方法可以做到这一点。您可以将其读入字符串并根据空格手动处理它。或者您可以使用stringstream将数值提取到array/vector中。但是,这仍然要求您在执行此操作之前删除该名称。

下面是一个小代码,用于将文件内容读取到unordered_map,该本质上是其他语言中定义的dictionary

void read_file(const std::string& path) {
std::ifstream in(path); // file stream to read file
std::unordered_map<std::string, std::vector<double>> map;
/*
* map structure to hold data, you do not have to use this.
* I am using it only for demonstration purposes.
* map takes string (name) as KEY and vector<double> as VALUE
* so given a NAME you can get the corresponding grades VECTOR
* i.e.: map["Johnson"] --> [85, 83, 77, 91, 76]
*/
std::string line;
while (std::getline(in, line)) { // read entire line
if (line == "") continue; // ignore empty lines
int last_alpha_idx = 0; // name ends when last alphabetic is encountered
for (size_t i = 0; i < line.size(); i++)
if (std::isalpha(line[i])) last_alpha_idx = i; // get index of last alpha
std::string name = line.substr(0, last_alpha_idx + 1); // name is from index 0 to last_alpha_idx inclusive (hence +1)
std::string numbers = line.substr(last_alpha_idx + 1); // array values the rest of the line after the name
std::stringstream ss(numbers); // this is an easy way to convert whitespace delimated string to array of numbers
double value;
while (ss >> value) // each iteration stops after whitespace is encountered
map[name].push_back(value);
}
}

你可以把它读到一个数组中,代码不会发生太大的变化。我选择string作为KEY,vector<double>作为VALUE,为字典(map(形成键/值对。

正如您在代码中看到的,它查找每行中的最后一个字母字符,并获取其索引以从读取行中提取名称。然后,它获取字符串的其余部分(只是数字(并将它们放入一个stringstream该将在其内部循环中单独提取每个数字。

注意:上面的代码支持全名(例如"Johnson Smith 85 83 77 91 76"(。