在C++中,可以使用getline()函数从输入流中读取一行文本,并将其存储到一个字符串中。如果要在单个for循环中使用getline()函数填充多个向量,可以使用istringstream类将读取的字符串转换为其他类型的数据。
下面是一个示例代码,演示了如何在单个for循环中使用getline()函数填充多个向量:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
int main() {
std::string input;
std::vector<int> intVector;
std::vector<float> floatVector;
std::vector<std::string> stringVector;
std::getline(std::cin, input); // 从输入流中读取一行文本
std::istringstream iss(input); // 创建一个字符串流
std::string token;
while (std::getline(iss, token, ' ')) { // 使用空格作为分隔符,将字符串分割为多个子字符串
int intValue;
float floatValue;
// 尝试将子字符串转换为整数
try {
intValue = std::stoi(token);
intVector.push_back(intValue);
} catch (const std::exception& e) {
// 如果转换失败,则尝试将子字符串转换为浮点数
try {
floatValue = std::stof(token);
floatVector.push_back(floatValue);
} catch (const std::exception& e) {
// 如果转换失败,则将子字符串作为字符串存储
stringVector.push_back(token);
}
}
}
// 输出填充后的向量内容
std::cout << "Int Vector: ";
for (const auto& value : intVector) {
std::cout << value << " ";
}
std::cout << std::endl;
std::cout << "Float Vector: ";
for (const auto& value : floatVector) {
std::cout << value << " ";
}
std::cout << std::endl;
std::cout << "String Vector: ";
for (const auto& value : stringVector) {
std::cout << value << " ";
}
std::cout << std::endl;
return 0;
}
在上述代码中,我们首先使用getline()函数从输入流中读取一行文本,并将其存储到input字符串中。然后,我们创建了一个istringstream对象iss,将input作为其构造函数的参数,从而创建了一个字符串流。接下来,我们使用getline()函数和空格作为分隔符,将字符串流中的内容分割为多个子字符串。对于每个子字符串,我们首先尝试将其转换为整数,如果转换成功,则将其存储到intVector中;如果转换失败,则尝试将其转换为浮点数,如果转换成功,则将其存储到floatVector中;如果转换失败,则将其作为字符串存储到stringVector中。最后,我们分别输出填充后的intVector、floatVector和stringVector的内容。
这种方法可以在单个for循环中使用getline()函数填充多个向量,但需要注意的是,如果输入的字符串中包含无法转换为整数或浮点数的子字符串,会抛出异常。因此,在实际应用中,需要根据具体情况进行错误处理。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云