我正在尝试运行一个程序,输出一些文本行然后退出(或者至少显示“按任意键继续”)当你输入“|”。但是,当我运行这个程序并输入'|' ,它只是说“按任意键继续”。所以它不会输出我想要的文本。
这是我试图实现目标的代码:
if(value == '|')
{
cout << lowest << lowest_unit << " is the lowest number.\n";
cout << highest << highest_unit << " is the highest number. \n";
break;
}
如果原因不在上面的代码中,那么这就是我程序的所有代码:
int main()
{
double value;
double realvalue;
double lowest = 0;
double highest = 0;
string unit;
string highest_unit;
string lowest_unit;
cout << "Please enter a number follow by a unit: ";
//convert units to cm for all
while (cin >>value>>unit)
{
if(unit=="cm")
{
realvalue = value;
}
else if(unit=="in")
{
realvalue = value*2.54;
}
else if(unit=="m"){
realvalue = value*100;
}
else if(unit=="ft")
{
realvalue = value*12*2.54;
}
else
{
cout << "Your units are incorrect.\n";
break;
}
if (lowest == 0 && highest == 0)
{
lowest = value;
highest = value;
lowest_unit = unit;
highest_unit = unit;
cout << lowest << highest_unit << " is the smallest so far.\n"
<< highest << lowest_unit <<" is the largest so far.\n";
}
else
{
if (realvalue < lowest)
{
lowest = value;
lowest_unit = unit;
cout << value << lowest_unit << " is the smallest so far.\n"
<< highest << highest_unit << " is still the highest.\n";
}
else
{
if (realvalue > highest)
{
highest = value;
highest_unit = unit;
cout << lowest << lowest_unit << " is still the lowest.\n"
<< highest << highest_unit << " is the largest so far.\n";
}
else
{
cout << lowest << lowest_unit << " is still the lowest.\n"
<< highest << highest_unit << " is still the highest.\n";
}
}
}
cout << "\nPlease enter another number: ";
if(value == '|')
{
cout << lowest << lowest_unit << " is the lowest number.\n";
cout << highest << highest_unit << " is the highest number. \n";
break;
}
}
}
(它基本上做的是比较用户输入的不同长度,然后决定哪个长度最小,哪个长度是用户输入的最大长度)。
如何实现我之前输出文本的目标(或更准确地说,同时)“按任意键继续”?
答案 0 :(得分:0)
value
是双倍的。当您输入|时,它不会被读作数字,并且value
不会被设置。相反,应在cin中设置失败位。
比较value == '|'
检查以查看value
是否等于ASCII字符的数值|,恰好是124,这不是你想要的。
答案 1 :(得分:0)
您的程序在循环中每次都需要两个输入。
如果要在第一个输入处停止,则需要分两步读取输入。
此外,您的value
是一个数字,而不是字符串,您无法以相同的方式读取数字和字符串。
while (1) {
string tmp;
if (!(cin >> tmp)) {
break;
}
if (tmp == "|") {
break;
}
//convert string into double
value = stod(tmp); //todo, check conversion was well done
if (! (cin >> unit) ) {
break;
}
// rest of code
}
答案 2 :(得分:0)
"|"
不能解释为double
,因此您应该使用std::string
来阅读输入。
您的代码应该是这样的:
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::stod;
using std::string;
int main()
{
double value;
double realvalue;
double lowest = 0;
double highest = 0;
string value_str;
string unit;
string highest_unit;
string lowest_unit;
cout << "Please enter a number follow by a unit: ";
//convert units to cm for all
while (cin >>value_str>>unit)
{
if (value_str == "|") // use string literal, not character constant
{
cout << lowest << lowest_unit << " is the lowest number.\n";
cout << highest << highest_unit << " is the highest number. \n";
break;
}
value = stod(value_str);
// do works with value and unit
cout << value << "\t" << unit << "\n";
}
}