[英]How to extract specific numerical values from a inputted string using cin?
1U = 1.2A
1U = 2.3B
1U = 3.4C
1U = 4.5D
1U = 5.6E
1U = 6.7F
1U = 7.8G
The code above is the input. 上面的代码是输入。 Is there a way to only extract the numbers from each line? 有没有一种方法只能从每行中提取数字? For example, in the first line, the only values I want is 1.2, not the "1U = " or the A after it. 例如,在第一行中,我想要的唯一值是1.2,而不是“ 1U =”或它后面的A。 I tried using regular cin and getline(), but they detect a string so they cannot receive any input. 我尝试使用常规cin和getline(),但是它们检测到字符串,因此它们无法接收任何输入。 I also tried using cin.ignore but I believe I used it incorrectly. 我也尝试使用cin.ignore,但我认为使用不正确。 This is what I have so far: 这是我到目前为止的内容:
double temp;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin >> temp;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
Will ignore a whole line. 将忽略整行。 But 但
cin.ignore(numeric_limits<streamsize>::max(), '=');
will ignore everything up to = so 将忽略一切,直到=为止
1U = 1.2A
1U = 2.3B
1U = 3.4C
would become 会成为
1.2A
1U = 2.3B
1U = 3.4C
Now you can 现在你可以
cin >> temp;
Which would read skip whitespace 1.2 into temp
and stop as soon as it finds something that cannot be a double
. 它将跳过空白1.2进入temp
并在发现不能为double
东西时立即停止。
A
1U = 2.3B
1U = 3.4C
then you loop back around to 然后您循环回去
cin.ignore(numeric_limits<streamsize>::max(), '=');
which will leave 将会离开
2.3B
1U = 3.4C
and 和
cin >> temp;
grabs 2.8 and then repeat again. 抓到2.8,然后再次重复。
Code for this could look like 此代码可能看起来像
while (cin.ignore(numeric_limits<streamsize>::max(), '=') &&
cin >> temp)
{
// use temp
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.