如果用户按下“ q”,我想退出循环,但是当我按下q时,它将进入无限循环。我的if语句有什么问题?为什么用户按下“ q”时无法识别?
library(dplyr)
dat2 %>%
mutate_if(is.factor, as.character) %>%
mutate(x = ifelse(V1 > V2, paste(V1, V2), paste(V2, V1))) %>%
inner_join(
dat1 %>%
mutate_if(is.factor, as.character) %>%
mutate(x = ifelse(V1 > V2, paste(V1, V2), paste(V2, V1))) %>%
select(-V1, -V2),
by = "x"
) %>%
select(V1, V2, V3 = V3.y, V4 = V3.x)
# V1 V2 V3 V4
#1 home cat date1 col1
#2 water fire date2 col2
#3 sofa TV date3 col3
#4 knife kitchen date4 col4
答案 0 :(得分:1)
这个想法是:读一个char
(不是数字);查看它是否等于q
。如果是,请退出。如果没有,请putback
char
,然后读取一个数字。
#include<iostream>
using namespace std;
int main()
{
char user_input; // note: changed it from string to char
double price;
while (true) // infinite loop; exit conditions are inside the loop
{
cin >> ws >> user_input; // note: it's important to discard whitespace
if (user_input == 'q') // note: changed from " to '
break;
// Note: for putback to succeed, it must be only 1 byte, cannot be a string
cin.putback(user_input);
if (!(cin >> price))
break; // note: exit on error
// Your code here
...
}
}
如果您希望用户键入exit
或其他超过1个字节的内容,则此想法将不起作用。如果需要这么长的退出命令,则必须使用传统的解析机制(读取输入行;将其与exit
命令进行比较;如果不相等,则为convert the string to a number)。