简体   繁体   English

从getline获取2个字符串变量

[英]Getting 2 string variables out of a getline

I'm curious if it's possible to put letters out of a getline function into 2 separate string variables, sorry if it's hard to understand but I'll explain this further. 我很好奇是否可以将getline函数中的字母放入2个单独的字符串变量中,如果很难理解,抱歉,我将进一步解释。

Let's say I have a 'string x;' 假设我有一个“字符串x;” variable, I use a 'getline(cin, x)' and then I were to run this and type in for example 'hello world'. 变量,我使用“ getline(cin,x)”,然后运行它并输入例如“ hello world”。 Would it be possible to put 'hello' and 'world' into 2 separate string variables? 是否可以将“ hello”和“ world”放入2个单独的字符串变量中?

For example: It will store the first letter keep on adding letters to a variable until it hits a whitespace, then keep on adding letters to the next variable until it reaches another whitespace. 例如:它将存储第一个字母,并继续向变量添加字母,直到到达空白为止,然后继续向下一个变量添加字母,直到到达另一个空白为止。

I understand I might have explained this poorly, and if it's not understandable let me know and I'll try explain more. 我知道我可能对此解释不佳,如果无法理解,请告诉我,我将尝试解释更多。

the stream operator>> functions already handle whitespace formatting for you, the canonical way to handle an unknown number of tokens on each line is to do something like the following: operator>>函数已经为您处理了空格格式,处理每行上未知数量的令牌的规范方法是执行以下操作:

std::string line;
getline(std::cin, line);

std::istringstream iss(line);
std::string token;
while (iss >> token) {
  // Do something with token
}

If you don't care about what kind of whitespace is used to separate the tokens this can be simplified to 如果您不关心使用哪种空格来分隔标记,可以将其简化为

std::string token;
while (std::cin >> token) {
  // Do something with token
}

You need a way to parse the string using a delimiter (in this case a space ' '). 您需要一种使用定界符(在本例中为空格'')解析字符串的方法。

This post has about a thousand different functions that can solve what you are trying to do. 这篇文章有大约一千种不同的功能,可以解决您想要做的事情。

Split a string in C++? 在C ++中拆分字符串?

Easiest way to do this if you know how many variables you will need would be to take advantage of the default std::cin implementation of using space as a delimiter: 如果您知道需要多少变量,最简单的方法就是利用默认的std :: cin实现,该实现使用空格作为定界符:

std::string x1, x2;          // define two strings
std::cin >> x1 >> x2;        // user enters "Hello World"
std::cout << x1 <<" "<< x2;  // x1 = "Hello", x2 = "World"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM