使用字符串流提取参数
Extracting arguments using stringstream
我想输入一个短语并提取短语的每个字符:
int main()
{
int i = 0;
string line, command;
getline(cin, line); //gets the phrase ex: hi my name is andy
stringstream lineStream(line);
lineStream>>command;
while (command[i]!=" ") //while the character isn't a whitespace
{
cout << command[i]; //print out each character
i++;
}
}
但是我得到错误:无法在 while 语句中比较指针和整数
正如标题"使用字符串流提取参数"所建议的那样:
我想你正在寻找这个:
getline(cin, line);
stringstream lineStream(line);
std::vector<std::string> commands; //Can use a vector to store the words
while (lineStream>>command)
{
std::cout <<command<<std::endl;
//commands.push_back(command); // Push the words in vector for later use
}
command
是一个字符串,所以command[i]
是一个字符。您无法将字符与字符串文本进行比较,但可以将它们与字符文本进行比较,例如
command[i]!=' '
但是,您不会在字符串中获得空格,因为输入运算符>>
读取空格分隔的"单词"。因此,您有未定义的行为,因为循环将继续超出字符串的范围。
您可能需要两个循环,一个外部从字符串流中读取,另一个内部从当前单词中获取字符。要么这样,要么在line
中循环字符串(我不建议这样做,因为空格字符比空格多)。或者当然,由于来自字符串流的"输入"已经是空格分隔的,只需打印字符串,无需循环字符。
若要从字符串流中提取所有单词并将其提取到字符串向量中,可以使用以下命令:
std::istringstream is(line);
std::vector<std::string> command_and_args;
std::copy(std::istream_iterator<std::string>(is),
std::istream_iterator<std::string>(),
std::back_inserter(command_and_args));
在上面的代码之后,向量command_and_args
包含字符串流中的所有空格分隔的单词,command_and_args[0]
是命令。
参考资料: std::istream_iterator
, std::back_inserter
, std::copy
.
相关文章:
- 将不同类型的模板参数包提取到双精度向量中会产生警告
- 如何提取模板参数中传递的类型
- C/C++预处理器:提取每秒的可变参数
- C++ 模板提取布尔参数
- 从模板参数的模板参数中提取值
- 使用C++元编程提取 C 函数的参数("Practical C++ Metaprogramming" 中的示例)
- 如何定义变体<x,y,z>提取模板参数的子类型
- 使用命令行参数从TXT文件中提取并在C 中运行特定类
- 为什么我只从可变参数模板中提取一个值?
- 提取模板参数的值
- C++从函数签名中提取参数
- 每个新客户端的 GStreamer 和 URI 查询参数提取
- 从文件名中提取文件名,路径来自参数
- 从参数包中提取成员类型
- 从boost ::函数中提取参数
- 使用字符串流提取参数
- 仅从decltype(someFunction)中提取参数类型列表
- 使用可变参数模板从 Lua 函数回调 (C api) 中提取参数
- 此代码如何从元组中提取参数
- 从Qt中包含的带引号区域的字符串中提取参数