C++ split string(C++ 拆分字符串)
问题描述
我正在尝试使用空格作为分隔符来分割字符串.我想将每个标记存储在一个数组或向量中.
I am trying to split a string using spaces as a delimiter. I would like to store each token in an array or vector.
我试过了.
string tempInput;
cin >> tempInput;
string input[5];
stringstream ss(tempInput); // Insert the string into a stream
int i=0;
while (ss >> tempInput){
input[i] = tempInput;
i++;
}
问题是,如果我输入这是一个测试",数组似乎只存储输入[0] =这个".它不包含 input[2] 到 input[4] 的值.
The problem is that if i input "this is a test", the array only seems to store input[0] = "this". It does not contain values for input[2] through input[4].
我也尝试过使用向量,但结果相同.
I have also tried using a vector but with the same result.
推荐答案
转到重复题学习如何将字符串拆分为单词,但您的方法实际上是正确的.实际问题在于您如何在尝试拆分输入之前 读取它:
Go to the duplicate questions to learn how to split a string into words, but your method is actually correct. The actual problem lies in how you are reading the input before trying to split it:
string tempInput;
cin >> tempInput; // !!!
当您使用 cin >>tempInput
,您只能从输入中获取第一个单词,而不是整个文本.有两种可能的方法来解决这个问题,其中最简单的方法是忘记 stringstream
并直接迭代输入:
When you use the cin >> tempInput
, you are only getting the first word from the input, not the whole text. There are two possible ways of working your way out of that, the simplest of which is forgetting about the stringstream
and directly iterating on input:
std::string tempInput;
std::vector< std::string > tokens;
while ( std::cin >> tempInput ) {
tokens.push_back( tempInput );
}
// alternatively, including algorithm and iterator headers:
std::vector< std::string > tokens;
std::copy( std::istream_iterator<std::string>( std::cin ),
std::istream_iterator<std::string>(),
std::back_inserter(tokens) );
这种方法将在单个向量中为您提供输入中的所有标记.如果您需要单独处理每一行,那么您应该使用 <string>
标头中的 getline
而不是 cin >>临时输入
:
This approach will give you all the tokens in the input in a single vector. If you need to work with each line separatedly then you should use getline
from the <string>
header instead of the cin >> tempInput
:
std::string tempInput;
while ( getline( std::cin, tempInput ) ) { // read line
// tokenize the line, possibly with your own code or
// any answer in the 'duplicate' question
}
这篇关于C++ 拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 拆分字符串


基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09