gpt4 book ai didi

C++ Stringstream : Accepts a string, 但不是存储在变量中的字符串。为什么?

转载 作者:太空宇宙 更新时间:2023-11-03 10:33:24 26 4
gpt4 key购买 nike

我一直在尝试将输入字符串拆分为由空格分隔的更小的字符串。我从 here 中找到了这段代码:

stringstream ss ("bla bla");
string s;

while (getline(ss, s, ' ')) {
cout << s << endl;
}

效果很好。但是,如果我用包含字符串的变量替换“bla bla”:

string userInput;
cin >> userInput;

stringstream ss (userInput);
string s;

while (getline(ss, s, ' ')) {
cout << s << endl;
}

只打印第一个单词/字符/字符串。这是为什么?有办法解决吗?我查看了一些 stringstream 问题,但问题是我真的不知道我在找什么。

最佳答案

您的问题不是 stringstream ss (userInput); , 这是 std::cin 的行为.任何空格都会结束格式化用户输入的提取,因此输入 bla bla将产生一个 std::string s = "bla"和另一个字符串 "bla"等待提取。

使用 cin >> noskipws >> userInput; 如果你想得到一行,使用 std::getline(std::cin,userInput)反而。看看这个小demonstration , 它比较 std::getlinestd::cin::operator>>根据您的输入 bla bla :

来源:

#include <iostream>
#include <string>

int main(){
std::string userInput;

std::cout << "Using std::getline(std::cin,userInput) on input \"bla bla\"." << std::endl;
std::getline(std::cin,userInput);
std::cout << "userInput contains \"" << userInput << "\"" << std::endl;

std::cout << "std::cin >> userInput on input \"bla bla\"." << std::endl;
std::cin >> userInput;
std::cout << "userInput contains \"" << userInput << "\"" << std::endl;
return 0;
}

结果:

Using std::getline(std::cin,userInput) on input "bla bla".userInput contains "bla bla"std::cin >> userInput on input "bla bla".userInput contains "bla"

另见:

关于C++ Stringstream : Accepts a string, 但不是存储在变量中的字符串。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9631720/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com