【发布时间】:2015-05-18 15:55:29
【问题描述】:
我最近在C++做一个问题:
编写一个程序来计算一系列 5 位数字是否连续 数字。为了让这更容易,假设数字是一个字符串:
字符串数字 = "10-9-8-7-6";
确保您的代码也适用于以下序列:
字符串数字 = "1-2-3-4-5";
我解决了它,但是我看到当我使用cin 作为字符串时,控制台窗口抛出了一些异常并且没有执行程序,但是用getline 替换它时,它工作得很好。
谁能解释一下它背后的原因,因为从逻辑上讲,两者都应该正常工作。
程序是:
#include<iostream>
#include<string>
using namespace std;
void change(int x, int y, int &inc, int &dec)
{
if (x - y == 1)
++dec;
else if (y - x == 1)
++inc;
}
int main()
{
string s = "", snum = "";
cout << "enter 5 nos and use \'-\' to separate them: ";
cin >> s;
int i = 0, x = 0, y = 0, inc = 0, dec = 0;
for (char &ch : s)
{
if (ch == '-')
{
++i;
if (i == 1)
{
y = stoi(snum);
cout << y << endl;
}
else
{
x = y;
y = stoi(snum);
cout << x << " " << y << endl;
change(x, y, inc, dec);
}
snum = "";
}
else
snum += ch;
}
x = y;
y = stoi(snum);
cout << x << " " << y << endl;
change(x, y, inc, dec);
if (inc == 4 || dec == 4)
cout << "ORDERED";
else
cout << "UNORDERED";
return 0;
}
【问题讨论】:
-
如果你给出的是失败的代码而不是工作代码,那会更容易回答。
-
我运行您的代码并没有遇到任何问题。你能清楚地解释你的问题吗?
-
只需将 getline(cin,s) 替换为 cin>>s