如何在C++中将一行内容分割并存储到vector<string>中?
嘿,我来帮你排查下这段代码的问题,再给你几个实用的解决方案~
首先,你的代码里有几个明显的问题导致它无法正常运行:
scanf返回值判断错误:scanf("%s", buffer)的返回值是成功读取的变量个数(成功时返回1,遇到输入结束或错误返回EOF),不是读取到的字符,所以你和'\n'比较完全不成立。而且%s格式符会自动跳过所有空白字符(空格、换行、制表符),它根本不会读到换行符,你的循环会一直跑直到输入终止。strcmp使用错误:strcmp要求两个参数都是C风格字符串(const char*),但你写的strcmp(buffer, ' ')里的' '是单个字符,类型不匹配,编译器肯定会报错。而且其实scanf("%s")已经帮你跳过空格了,读进来的buffer本身就是一个完整的单词,根本不需要判断是不是空格。- 缓冲区溢出风险:固定大小的
char buffer[100]很危险,如果输入的单词长度超过99,就会触发缓冲区溢出,导致程序崩溃或其他未定义行为。
下面给你几个符合C++风格的正确解法:
方法一:直接用cin读取所有单词(简单通用)
cin默认就以空白字符作为分隔符读取字符串,自动处理内存,完全不用担心溢出问题。这个方法会读取所有输入里的单词,直到输入结束:
#include <iostream> #include <vector> #include <string> int main() { std::vector<std::string> something; std::string word; // 当成功读取到单词时,循环继续;输入结束时cin会变为false while (std::cin >> word) { something.push_back(word); } // 测试输出结果 for (const auto& w : something) { std::cout << w << '\n'; } return 0; }
方法二:读取单行并拆分单词(严格匹配你的需求)
如果你只想读取一行内的单词,那可以先用getline读取整行,再用stringstream拆分这一行的内容:
#include <iostream> #include <vector> #include <string> #include <sstream> int main() { std::vector<std::string> something; std::string line; // 读取整行内容,直到遇到换行符(换行符会被丢弃) if (std::getline(std::cin, line)) { std::istringstream iss(line); std::string word; // 从stringstream中逐个读取单词,同样以空白分隔 while (iss >> word) { something.push_back(word); } } // 测试输出结果 for (const auto& w : something) { std::cout << w << '\n'; } return 0; }
(不推荐)用C风格函数修正的版本
如果你一定要用C的输入函数,那可以用fgets读取整行,再用strtok拆分,但要注意缓冲区大小限制:
#include <iostream> #include <vector> #include <string> #include <cstdio> #include <cstring> int main() { std::vector<std::string> something; char buffer[100]; // 读取整行到缓冲区 if (std::fgets(buffer, sizeof(buffer), stdin)) { // 去掉末尾的换行符(如果存在) buffer[std::strcspn(buffer, "\n")] = '\0'; char* token = std::strtok(buffer, " "); // 逐个拆分单词 while (token != nullptr) { something.push_back(token); token = std::strtok(nullptr, " "); } } // 测试输出结果 for (const auto& w : something) { std::cout << w << '\n'; } return 0; }
不过这个方法如果输入的一行超过99字符会被截断,所以还是优先推荐前两种C++风格的写法哦。
内容的提问来源于stack exchange,提问作者Andrew T
相关产品推荐
相关产品推荐

