如何将文本文件每行的单词拆分存入不同的string vector?
读取文本文件分离物体与颜色到向量的实现方法
针对你的需求,有两种简单直接的实现方式,用C++标准库就能搞定,不用额外的拆分工具:
方法一:直接用cin按空格读取
cin默认会以空格、换行符作为分隔符,所以可以直接循环读取两个字符串,分别存入对应的向量。代码如下:
#include <iostream> #include <fstream> #include <vector> #include <string> int main() { std::vector<std::string> objects; std::vector<std::string> colors; std::ifstream input_file("your_file.txt"); // 替换成你的文件名 if (!input_file.is_open()) { std::cerr << "无法打开文件" << std::endl; return 1; } std::string obj, color; // 循环读取,直到文件末尾 while (input_file >> obj >> color) { objects.push_back(obj); colors.push_back(color); } input_file.close(); // 测试输出验证结果 for (size_t i = 0; i < objects.size(); ++i) { std::cout << "物体: " << objects[i] << ",颜色: " << colors[i] << std::endl; } return 0; }
这种方法最省心,不管每行两个单词之间有几个空格,cin都会自动跳过,只要格式符合要求就能正确读取。
方法二:按行读取后拆分
如果需要先处理整行内容(比如过滤空行、处理格式错误的行),可以先按行读取,再用istringstream拆分每行的两个单词:
#include <iostream> #include <fstream> #include <vector> #include <string> #include <sstream> int main() { std::vector<std::string> objects; std::vector<std::string> colors; std::ifstream input_file("your_file.txt"); if (!input_file.is_open()) { std::cerr << "无法打开文件" << std::endl; return 1; } std::string line; while (std::getline(input_file, line)) { // 跳过空行 if (line.empty()) continue; std::istringstream line_stream(line); std::string obj, color; // 从行流中读取两个单词 if (line_stream >> obj >> color) { objects.push_back(obj); colors.push_back(color); } else { std::cerr << "行格式错误: " << line << std::endl; } } input_file.close(); // 测试输出验证结果 for (size_t i = 0; i < objects.size(); ++i) { std::cout << "物体: " << objects[i] << ",颜色: " << colors[i] << std::endl; } return 0; }
这个方法能跳过空行,还能对格式不符合要求的行给出提示,容错性更强。
两种方法都基于C++标准库实现,你可以根据自己的实际需求选择使用。
内容的提问来源于stack exchange,提问作者maheema chowdhury
相关产品推荐
相关产品推荐

